From 28cc8a19baf25cce1421ac83e05bec7aab9412ba Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Wed, 21 Jun 2023 16:46:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E9=80=9A=E7=94=A8?= =?UTF-8?q?=E7=9A=84config.tpl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- goctl_template/api/config.tpl | 3 + server/faq/etc/faq.yaml | 8 ++ server/faq/faq.go | 49 ++++++++++++ server/faq/internal/config/config.go | 13 ++++ server/faq/internal/handler/routes.go | 22 ++++++ .../internal/handler/wetsetsettinghandler.go | 78 +++++++++++++++++++ .../faq/internal/logic/wetsetsettinglogic.go | 34 ++++++++ server/faq/internal/svc/servicecontext.go | 56 +++++++++++++ server/faq/internal/types/types.go | 61 +++++++++++++++ 9 files changed, 324 insertions(+) create mode 100644 server/faq/etc/faq.yaml create mode 100644 server/faq/faq.go create mode 100644 server/faq/internal/config/config.go create mode 100644 server/faq/internal/handler/routes.go create mode 100644 server/faq/internal/handler/wetsetsettinghandler.go create mode 100644 server/faq/internal/logic/wetsetsettinglogic.go create mode 100644 server/faq/internal/svc/servicecontext.go create mode 100644 server/faq/internal/types/types.go diff --git a/goctl_template/api/config.tpl b/goctl_template/api/config.tpl index 55127efb..78514f2e 100644 --- a/goctl_template/api/config.tpl +++ b/goctl_template/api/config.tpl @@ -1,9 +1,12 @@ package config import {{.authImport}} +import "fusenapi/server/faq/internal/types" type Config struct { rest.RestConf + SourceMysql string + Auth types.Auth {{.auth}} {{.jwtTrans}} } diff --git a/server/faq/etc/faq.yaml b/server/faq/etc/faq.yaml new file mode 100644 index 00000000..c5603f5c --- /dev/null +++ b/server/faq/etc/faq.yaml @@ -0,0 +1,8 @@ +Name: faq +Host: 0.0.0.0 +Port: 8888 +SourceMysql: "" +Auth: + AccessSecret: fusen2023 + AccessExpire: 604800 + RefreshAfter: 345600 \ No newline at end of file diff --git a/server/faq/faq.go b/server/faq/faq.go new file mode 100644 index 00000000..2ba13d77 --- /dev/null +++ b/server/faq/faq.go @@ -0,0 +1,49 @@ +package main + +import ( + "flag" + "fmt" + + "fusenapi/server/faq/internal/config" + "fusenapi/server/faq/internal/handler" + "fusenapi/server/faq/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/faq.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + 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() +} + +// var testConfigFile = flag.String("f", "../etc/faq.yaml", "the config file") +// var cnf config.Config + +// func GetTestServer() *rest.Server { +// flag.Parse() + +// conf.MustLoad(*testConfigFile, &cnf) + +// server := rest.MustNewServer(cnf.RestConf) +// defer server.Stop() + +// ctx := svc.NewServiceContext(cnf) +// handler.RegisterHandlers(server, ctx) + +// fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port) +// return server +// } diff --git a/server/faq/internal/config/config.go b/server/faq/internal/config/config.go new file mode 100644 index 00000000..4f528866 --- /dev/null +++ b/server/faq/internal/config/config.go @@ -0,0 +1,13 @@ +package config + +import ( + "fusenapi/server/faq/internal/types" + + "github.com/zeromicro/go-zero/rest" +) + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth +} diff --git a/server/faq/internal/handler/routes.go b/server/faq/internal/handler/routes.go new file mode 100644 index 00000000..b328b683 --- /dev/null +++ b/server/faq/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/faq/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodGet, + Path: "/web-set/setting", + Handler: WetSetSettingHandler(serverCtx), + }, + }, + ) +} diff --git a/server/faq/internal/handler/wetsetsettinghandler.go b/server/faq/internal/handler/wetsetsettinghandler.go new file mode 100644 index 00000000..d898c341 --- /dev/null +++ b/server/faq/internal/handler/wetsetsettinghandler.go @@ -0,0 +1,78 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/faq/internal/logic" + "fusenapi/server/faq/internal/svc" + "fusenapi/server/faq/internal/types" +) + +func WetSetSettingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var ( + // 定义错误变量 + err error + // 定义用户信息变量 + userinfo *auth.UserInfo + ) + // 解析JWT token,并对空用户进行判断 + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, // 返回401状态码,表示未授权 + Message: "unauthorized", // 返回未授权信息 + }) + logx.Info("unauthorized:", err.Error()) // 记录错误日志 + return + } + + if claims != nil { + // 从token中获取对应的用户信息 + userinfo, err = auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + } else { + // 如果claims为nil,则认为用户身份为白板用户 + userinfo = &auth.UserInfo{UserId: 0, GuestId: 0} + } + + var req types.Request + // 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 + if err := httpx.Parse(r, &req); err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + // 创建一个业务逻辑层实例 + l := logic.NewWetSetSettingLogic(r.Context(), svcCtx) + resp := l.WetSetSetting(&req, userinfo) + // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/server/faq/internal/logic/wetsetsettinglogic.go b/server/faq/internal/logic/wetsetsettinglogic.go new file mode 100644 index 00000000..3806422d --- /dev/null +++ b/server/faq/internal/logic/wetsetsettinglogic.go @@ -0,0 +1,34 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/faq/internal/svc" + "fusenapi/server/faq/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type WetSetSettingLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewWetSetSettingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WetSetSettingLogic { + return &WetSetSettingLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *WetSetSettingLogic) WetSetSetting(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/faq/internal/svc/servicecontext.go b/server/faq/internal/svc/servicecontext.go new file mode 100644 index 00000000..78519b9a --- /dev/null +++ b/server/faq/internal/svc/servicecontext.go @@ -0,0 +1,56 @@ +package svc + +import ( + "errors" + "fmt" + "fusenapi/server/faq/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 +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + } +} + +func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + 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)) +} diff --git a/server/faq/internal/types/types.go b/server/faq/internal/types/types.go new file mode 100644 index 00000000..705841f7 --- /dev/null +++ b/server/faq/internal/types/types.go @@ -0,0 +1,61 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +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"` +} + +// 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 +}