From d4d4fd3f795f81b3bee592aba394e58bba8f1f5b Mon Sep 17 00:00:00 2001 From: XiaoLFeng Date: Mon, 25 Dec 2023 02:19:00 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=9A=E7=94=A8=E6=93=8D=E4=BD=9C=E5=B1=9E?= =?UTF-8?q?=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/interface.go | 4 ++ go.mod | 2 + go.sum | 4 ++ internal/middleware/GlobalMiddleware.go | 39 ---------- internal/middleware/globalMiddleware.go | 96 +++++++++++++++++++++++++ main.go | 1 + utility/ErrorCode/ErrorCode.go | 29 ++++++++ utility/Processing/Processing.go | 30 ++++++++ utility/ResultUtil.go | 50 +++++++++++++ 9 files changed, 216 insertions(+), 39 deletions(-) delete mode 100644 internal/middleware/GlobalMiddleware.go create mode 100644 internal/middleware/globalMiddleware.go create mode 100644 utility/ErrorCode/ErrorCode.go create mode 100644 utility/Processing/Processing.go create mode 100644 utility/ResultUtil.go diff --git a/api/interface.go b/api/interface.go index afa1a7f..f774a52 100644 --- a/api/interface.go +++ b/api/interface.go @@ -16,3 +16,7 @@ type IHelloV1 interface { type IAuthV1 interface { AuthRegister(ctx context.Context, req *request.RegisterReq) (res *request.RegisterRes, err error) } + +type ITokenV1 interface { + TokenCreate(ctx context.Context, req *request.TokenCreateReq) (res *request.TokenCreateRes, err error) +} diff --git a/go.mod b/go.mod index 03cd04f..827cd4a 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,8 @@ require ( github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-logr/logr v1.4.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-sql-driver/mysql v1.7.1 // indirect + github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.1 // indirect github.com/gorilla/websocket v1.5.1 // indirect github.com/grokify/html-strip-tags-go v0.1.0 // indirect github.com/magiconair/properties v1.8.7 // indirect diff --git a/go.sum b/go.sum index e510ca9..6fb3f4d 100644 --- a/go.sum +++ b/go.sum @@ -20,6 +20,10 @@ github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= +github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.1 h1:5VW1vlaFNSHHhMliRkGTcDshMeA52Il8T+gffJJaVMc= +github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.1/go.mod h1:jxCa1WV/W+q0F4ILebakUsqRrl7iL3qvP+Uci0eXAew= github.com/gogf/gf/v2 v2.6.1 h1:n/cfXM506WjhPa6Z1CEDuHNM1XZ7C8JzSDPn2AfuxgQ= github.com/gogf/gf/v2 v2.6.1/go.mod h1:x2XONYcI4hRQ/4gMNbWHmZrNzSEIg20s2NULbzom5k0= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= diff --git a/internal/middleware/GlobalMiddleware.go b/internal/middleware/GlobalMiddleware.go deleted file mode 100644 index c3fada6..0000000 --- a/internal/middleware/GlobalMiddleware.go +++ /dev/null @@ -1,39 +0,0 @@ -package middleware - -import ( - "github.com/gogf/gf/v2/frame/g" - "github.com/gogf/gf/v2/net/ghttp" - "github.com/gogf/gf/v2/text/gregex" - "strconv" - "time" -) - -// TimestampMiddleware -// -// 全局中间件 -// 检查时间戳误差是否在 -func TimestampMiddleware(r *ghttp.Request) { - // 检查时间戳误差是否在 - timestamp, err := strconv.ParseInt(r.GetHeader("timestamp"), 10, 64) - if gregex.IsMatch(`^[0-9]{13,14}$`, []byte(strconv.FormatInt(timestamp, 10))) { - if timestamp+int64(2000) > time.Now().UnixMilli() && timestamp-int64(2000) < time.Now().UnixMilli() { - r.Middleware.Next() - } else { - if err != nil { - r.Response.WriteJson(g.Map{ - "code": 40011, - "message": "时间戳过期", - "data": nil, - }) - } - } - } else { - if err != nil { - r.Response.WriteJson(g.Map{ - "code": 40010, - "message": "时间戳格式错误", - "data": nil, - }) - } - } -} diff --git a/internal/middleware/globalMiddleware.go b/internal/middleware/globalMiddleware.go new file mode 100644 index 0000000..42729f2 --- /dev/null +++ b/internal/middleware/globalMiddleware.go @@ -0,0 +1,96 @@ +package middleware + +import ( + "github.com/gogf/gf/v2/errors/gerror" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" + "github.com/gogf/gf/v2/text/gregex" + "net/http" + "strconv" + "time" +) + +// DefaultHandlerResponse is the default implementation of HandlerResponse. +type DefaultHandlerResponse struct { + Code int `json:"code" dc:"Error code"` + Message string `json:"message" dc:"Error message"` + Data interface{} `json:"data" dc:"Result data for certain request according API definition"` +} + +// TimestampMiddleware +// +// 全局中间件 +// 检查时间戳误差是否在 +func TimestampMiddleware(r *ghttp.Request) { + // 检查时间戳误差是否在 + timestamp, err := strconv.ParseInt(r.GetHeader("timestamp"), 10, 64) + if gregex.IsMatch(`^[0-9]{13,14}$`, []byte(strconv.FormatInt(timestamp, 10))) { + if timestamp+int64(2000) > time.Now().UnixMilli() && timestamp-int64(2000) < time.Now().UnixMilli() { + r.Middleware.Next() + } else { + if err != nil { + r.Response.WriteJson(g.Map{ + "code": 40011, + "message": "时间戳过期", + "data": nil, + }) + } + } + } else { + if err != nil { + r.Response.WriteJson(g.Map{ + "code": 40010, + "message": "时间戳格式错误", + "data": nil, + }) + } + } +} + +func JsonResponseMiddleware(r *ghttp.Request) { + r.Middleware.Next() + + // There's custom buffer content, it then exits current handler. + if r.Response.BufferLength() > 0 { + return + } + + var ( + msg = r.GetRequest("message").String() + err = r.GetError() + res = r.GetHandlerResponse() + code int + ) + if err != nil { + if r.GetRequest("code") == nil { + code = 500 + } + msg = err.Error() + } else { + if r.Response.Status > 0 && r.Response.Status != 200 { + msg = http.StatusText(r.Response.Status) + switch r.Response.Status { + case http.StatusNotFound: + code = 404 + case http.StatusForbidden: + code = 403 + default: + code = r.GetRequest("code").Int() + } + // 处理错误 + err = gerror.New(r.GetRequest("message").String()) + r.SetError(err) + } else { + code = 200 + if msg == "" { + msg = "success" + } + } + } + + r.Response.WriteJson(DefaultHandlerResponse{ + Code: code, + Message: msg, + Data: res, + }) +} diff --git a/main.go b/main.go index 52f2492..368b2e2 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( _ "PersonalMain/internal/packed" + _ "github.com/gogf/gf/contrib/drivers/mysql/v2" "github.com/gogf/gf/v2/os/gctx" diff --git a/utility/ErrorCode/ErrorCode.go b/utility/ErrorCode/ErrorCode.go new file mode 100644 index 0000000..8e31808 --- /dev/null +++ b/utility/ErrorCode/ErrorCode.go @@ -0,0 +1,29 @@ +package ErrorCode + +type ErrorCode struct { + output string + code int + message string +} + +type Errors interface { + Output() string + Code() int + Message() string +} + +var ( + NoneDataResult = ErrorCode{output: "success", code: 200, message: "success"} +) + +func (e ErrorCode) Output() string { + return e.output +} + +func (e ErrorCode) Code() int { + return e.code +} + +func (e ErrorCode) Message() string { + return e.message +} diff --git a/utility/Processing/Processing.go b/utility/Processing/Processing.go new file mode 100644 index 0000000..3d13932 --- /dev/null +++ b/utility/Processing/Processing.go @@ -0,0 +1,30 @@ +package Processing + +import ( + "math/rand" + "strconv" + "time" +) + +// CreateToken +// +// 生成 token +func CreateToken() string { + token := strconv.FormatInt(time.Now().UnixMilli(), 10) + if len(token) <= 13 { + token = "0" + token + } + token += "-" + for i := 0; i < 20; i++ { + if rand.Intn(2) == 0 { + token += strconv.Itoa(rand.Intn(10)) + } else { + token += string(byte(rand.Intn(26) + 97)) + } + } + token += "-" + for i := 0; i < 14; i++ { + token += strconv.Itoa(rand.Intn(10)) + } + return token +} diff --git a/utility/ResultUtil.go b/utility/ResultUtil.go new file mode 100644 index 0000000..8b0cf16 --- /dev/null +++ b/utility/ResultUtil.go @@ -0,0 +1,50 @@ +package utility + +import ( + "PersonalMain/utility/ErrorCode" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/net/ghttp" +) + +type DataResult struct{} + +// Success +// +// 内容输出(包含 data) +func Success(req *ghttp.Request, message string, data interface{}) { + req.Response.WriteJson(g.Map{ + "output": "Success", + "code": 200, + "message": message, + "data": data, + }) +} + +// SuccessNoData +// +// 内容输出(不含 data) +func SuccessNoData(req *ghttp.Request, message string) { + req.Response.WriteJson(g.Map{ + "output": "Success", + "code": 200, + "message": message, + }) +} + +func Error(req *ghttp.Request, errorCode ErrorCode.ErrorCode, data interface{}) { + req.Response.WriteJson(g.Map{ + "output": errorCode.Output(), + "code": errorCode.Code(), + "message": errorCode.Message(), + "data": data, + }) +} + +func ErrorDefault(req *ghttp.Request, output string, code int, message string, data interface{}) { + req.Response.WriteJson(g.Map{ + "output": output, + "code": code, + "message": message, + "data": data, + }) +}