This commit is contained in:
laodaming 2023-08-14 15:08:24 +08:00
commit 13c6eea1a8
18 changed files with 601 additions and 2 deletions

View File

@ -1,8 +1,15 @@
package gmodel
import "context"
import (
"context"
"fusenapi/utils/handlers"
"reflect"
"gorm.io/gorm"
)
// TODO: 使用model的属性做你想做的
func (m *FsMerchantCategoryModel) FindOne(ctx context.Context, id int64) (resp *FsMerchantCategory, err error) {
err = m.db.WithContext(ctx).Model(&FsMerchantCategory{}).Where("id = ? and status = ?", id, 1).Take(&resp).Error
return resp, err
@ -11,3 +18,37 @@ func (m *FsMerchantCategoryModel) FindRandOne(ctx context.Context) (resp *FsMerc
err = m.db.WithContext(ctx).Model(&FsMerchantCategory{}).Where("status = ?", 1).Order("RAND()").Take(&resp).Error
return resp, err
}
func (m *FsMerchantCategoryModel) BuilderDB(ctx context.Context, selectData []string) *gorm.DB {
if selectData != nil {
return m.db.WithContext(ctx).Select(selectData)
} else {
return m.db.WithContext(ctx).Select("*")
}
}
func (m *FsMerchantCategoryModel) FindAll(gormDB *gorm.DB, filterMap map[string]string, orderBy string) ([]*FsMerchantCategory, error) {
var resp []*FsMerchantCategory
// 过滤
if filterMap != nil {
gormDB = gormDB.Scopes(handlers.FilterData(filterMap))
}
// 排序
if orderBy != "" {
var fieldsMap = make(map[string]struct{})
s := reflect.TypeOf(&FsOrder{}).Elem() //通过反射获取type定义
for i := 0; i < s.NumField(); i++ {
fieldsMap[s.Field(i).Tag.Get("json")] = struct{}{}
}
gormDB = gormDB.Scopes(handlers.OrderCheck(orderBy, fieldsMap))
}
result := gormDB.Find(&resp)
if result.Error != nil {
return nil, result.Error
} else {
return resp, nil
}
}

View File

@ -1,2 +1,44 @@
package gmodel
// TODO: 使用model的属性做你想做的
// TODO: 使用model的属性做你想做的
import (
"context"
"fusenapi/utils/handlers"
"gorm.io/gorm"
)
// TODO: 使用model的属性做你想做的
func (m *FsUserInfoModel) BuilderDB(ctx context.Context, selectData []string) *gorm.DB {
if selectData != nil {
return m.db.WithContext(ctx).Select(selectData)
} else {
return m.db.WithContext(ctx).Select("*")
}
}
func (m *FsUserInfoModel) FindOne(gormDB *gorm.DB, filterMap map[string]string) (*FsUserInfo, error) {
var resp FsUserInfo
if filterMap != nil {
gormDB = gormDB.Scopes(handlers.FilterData(filterMap))
}
result := gormDB.Limit(1).Find(&resp)
if result.Error != nil {
return nil, result.Error
} else {
return &resp, nil
}
}
func (p *FsUserInfoModel) CreateOrUpdate(gormDB *gorm.DB, req *FsUserInfo) (resp *FsUserInfo, err error) {
if req.Id > 0 {
err = gormDB.Save(req).Error
} else {
err = gormDB.Create(req).Error
}
return req, err
}

36
server/base/base.go Normal file
View File

@ -0,0 +1,36 @@
package main
import (
"flag"
"fmt"
"net/http"
"time"
"fusenapi/utils/auth"
"fusenapi/server/base/internal/config"
"fusenapi/server/base/internal/handler"
"fusenapi/server/base/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/base.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
c.Timeout = int64(time.Second * 15)
server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) {
}))
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}

9
server/base/base_test.go Normal file
View File

@ -0,0 +1,9 @@
package main
import (
"testing"
)
func TestMain(t *testing.T) {
main()
}

10
server/base/etc/base.yaml Normal file
View File

@ -0,0 +1,10 @@
Name: base
Host: 0.0.0.0
Port: 9920
Timeout: 15000 #服务超时时间(毫秒)
SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023
AccessExpire: 2592000
RefreshAfter: 1592000
SourceRabbitMq: amqp://rabbit001:rabbit001129@110.41.19.98:5672

View File

@ -0,0 +1,14 @@
package config
import (
"fusenapi/server/base/internal/types"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
SourceMysql string
Auth types.Auth
SourceRabbitMq string
}

View File

@ -0,0 +1,35 @@
package handler
import (
"net/http"
"reflect"
"fusenapi/utils/basic"
"fusenapi/server/base/internal/logic"
"fusenapi/server/base/internal/svc"
"fusenapi/server/base/internal/types"
)
func MerchantCategoryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.MerchantCategoryListReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewMerchantCategoryListLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.MerchantCategoryList(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)
}
}
}

View File

@ -0,0 +1,22 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/server/base/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/api/base/merchant_category_list",
Handler: MerchantCategoryListHandler(serverCtx),
},
},
)
}

View File

@ -0,0 +1,53 @@
package logic
import (
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"context"
"fusenapi/server/base/internal/svc"
"fusenapi/server/base/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type MerchantCategoryListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewMerchantCategoryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MerchantCategoryListLogic {
return &MerchantCategoryListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *MerchantCategoryListLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *MerchantCategoryListLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *MerchantCategoryListLogic) MerchantCategoryList(req *types.MerchantCategoryListReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
fsMerchantCategoryModel := gmodel.NewFsMerchantCategoryModel(l.svcCtx.MysqlConn)
BuilderDB := fsMerchantCategoryModel.BuilderDB(l.ctx, nil).Model(&gmodel.FsMerchantCategory{})
resourceInfo, err := fsMerchantCategoryModel.FindAll(BuilderDB, nil, "sort desc")
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeDbSqlErr, "MerchantCategoryList error system failed")
}
// 返回成功
return resp.SetStatus(basic.CodeOK, map[string]interface{}{
"list": resourceInfo,
})
}

View File

@ -0,0 +1,62 @@
package svc
import (
"errors"
"fmt"
"fusenapi/server/base/internal/config"
"net/http"
"fusenapi/initalize"
"fusenapi/model/gmodel"
"github.com/golang-jwt/jwt"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
MysqlConn *gorm.DB
AllModels *gmodel.AllModelsGen
RabbitMq *initalize.RabbitMqHandle
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: initalize.InitMysql(c.SourceMysql),
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
RabbitMq: initalize.InitRabbitMq(c.SourceRabbitMq, nil),
}
}
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if AuthKey == "" {
return nil, nil
}
AuthKey = AuthKey[7:]
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return []byte(svcCtx.Config.Auth.AccessSecret), nil
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}

View File

@ -0,0 +1,78 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type MerchantCategoryListReq struct {
}
type Request struct {
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
}
type Auth struct {
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
RefreshAfter int64 `json:"refreshAfter"`
}
type File struct {
Filename string `fsfile:"filename"`
Header map[string][]string `fsfile:"header"`
Size int64 `fsfile:"size"`
Data []byte `fsfile:"data"`
}
type Meta struct {
TotalCount int64 `json:"totalCount"`
PageCount int64 `json:"pageCount"`
CurrentPage int `json:"currentPage"`
PerPage int `json:"perPage"`
}
// Set 设置Response的Code和Message值
func (resp *Response) Set(Code int, Message string) *Response {
return &Response{
Code: Code,
Message: Message,
}
}
// Set 设置整个Response
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
return &Response{
Code: Code,
Message: Message,
Data: Data,
}
}
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
Message: msg,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}

View File

@ -102,6 +102,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/api/user/one-more-order",
Handler: UserAgainOrderHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/api/user/set_user_info",
Handler: UserInfoSetHandler(serverCtx),
},
},
)
}

View File

@ -0,0 +1,35 @@
package handler
import (
"net/http"
"reflect"
"fusenapi/utils/basic"
"fusenapi/server/home-user-auth/internal/logic"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
)
func UserInfoSetHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UserInfoSetReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewUserInfoSetLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.UserInfoSet(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)
}
}
}

View File

@ -0,0 +1,95 @@
package logic
import (
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/utils/validate"
"time"
"context"
"fusenapi/server/home-user-auth/internal/svc"
"fusenapi/server/home-user-auth/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type UserInfoSetLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUserInfoSetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserInfoSetLogic {
return &UserInfoSetLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *UserInfoSetLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *UserInfoSetLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *UserInfoSetLogic) UserInfoSet(req *types.UserInfoSetReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
if userinfo.IsOnlooker() {
// 如果是,返回未授权的错误码
return resp.SetStatus(basic.CodeUnAuth)
}
var userId int64
var guestId int64
// 检查用户是否是游客
if userinfo.IsGuest() {
// 如果是使用游客ID和游客键名格式
guestId = userinfo.GuestId
} else {
// 否则使用用户ID和用户键名格式
userId = userinfo.UserId
}
_, err := validate.Validate(&req.Module, &req.Metadata)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeRequestParamsErr, "UserInfoSet error Validate failed")
}
// 根据模块类型检查数据
var userInfo = &gmodel.FsUserInfo{}
fsUserInfoModel := gmodel.NewFsUserInfoModel(l.svcCtx.MysqlConn)
BuilderDB := fsUserInfoModel.BuilderDB(l.ctx, nil).Model(&gmodel.FsUserInfo{})
BuilderDB1 := BuilderDB.Where("module = ?", req.Module).Where("user_id=?", userId).Where("guest_id=?", guestId)
userInfo, err = fsUserInfoModel.FindOne(BuilderDB1, nil)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeDbSqlErr, "UserInfoSet error system failed")
}
var nowTime = time.Now().Unix()
if userInfo.Id != 0 {
userInfo.Metadata = &req.Metadata
userInfo.Utime = &nowTime
} else {
userInfo.GuestId = &guestId
userInfo.UserId = &userId
userInfo.Module = &req.Module
userInfo.Metadata = &req.Metadata
userInfo.Ctime = &nowTime
}
_, err = fsUserInfoModel.CreateOrUpdate(BuilderDB, userInfo)
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeDbSqlErr, "UserInfoSet error system failed")
}
return resp.SetStatus(basic.CodeOK)
}

View File

@ -5,6 +5,11 @@ import (
"fusenapi/utils/basic"
)
type UserInfoSetReq struct {
Module string `form:"module,options=[merchant_category]"` // json格式字符串
Metadata string `form:"metadata"` // json格式字符串
}
type UserAgainOrderReq struct {
Sn string `form:"sn"` // 订单编号
}

20
server_api/base.api Normal file
View File

@ -0,0 +1,20 @@
syntax = "v1"
info (
title: // TODO: add title
desc: // TODO: add description
author: ""
email: ""
)
import "basic.api"
service base {
@handler MerchantCategoryListHandler
get /api/base/merchant_category_list(MerchantCategoryListReq) returns (response);
}
type (
MerchantCategoryListReq {
}
)

View File

@ -75,8 +75,19 @@ service home-user-auth {
// 再来一单
@handler UserAgainOrderHandler
get /api/user/one-more-order (UserAgainOrderReq) returns (response);
// 保存商户信息
@handler UserInfoSetHandler
post /api/user/set_user_info (UserInfoSetReq) returns (response);
}
type (
UserInfoSetReq {
Module string `form:"module,options=[merchant_category]"` // json格式字符串
Metadata string `form:"metadata"` // json格式字符串
}
)
type (
UserAgainOrderReq {
Sn string `form:"sn"` // 订单编号

View File

@ -0,0 +1,26 @@
package validate
import (
"encoding/json"
"errors"
)
type MerchantCategory struct {
CategoryId int64 `json:"category_id"`
}
func Validate(module *string, metadata *string) (interface{}, error) {
if *module == "merchant_category" {
var merchantCategory MerchantCategory
err := json.Unmarshal([]byte(*metadata), &merchantCategory)
if err != nil {
return nil, err
} else {
if merchantCategory.CategoryId == 0 {
return nil, errors.New("merchant_category.category_id is required")
}
return merchantCategory, nil
}
}
return nil, nil
}