yuleduiPay/middle/middle.go

77 lines
1.8 KiB
Go
Raw Permalink Normal View History

2024-11-05 08:32:10 +08:00
package middle
import (
"net/http"
"github.com/gogf/gf/errors/gcode"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// 跨域设置
func MiddlewareCORS(r *ghttp.Request) {
r.Response.CORSDefault()
r.Middleware.Next()
}
2024-11-18 09:15:45 +08:00
func LoggingMiddleware(r *ghttp.Request) {
// 获取请求的 URL 路径
//g.Log().Line().Print(nil, r.URL.Path)
g.Log().Line().Print(nil, r.URL.Path, ":", r.GetBody())
r.Middleware.Next()
}
2024-11-05 08:32:10 +08:00
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"`
}
// 返回值统一处理
func MiddlewareHandlerResponse(r *ghttp.Request) {
2024-11-18 09:15:45 +08:00
2024-11-05 08:32:10 +08:00
r.Middleware.Next()
// There's custom buffer content, it then exits current handler.
if r.Response.BufferLength() > 0 {
return
}
var (
msg string
err = r.GetError()
res = r.GetHandlerResponse()
code = gerror.Code(err)
)
if err != nil {
if code == gcode.CodeNil {
code = gcode.CodeInternalError
}
msg = err.Error()
} else {
if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
msg = http.StatusText(r.Response.Status)
switch r.Response.Status {
case http.StatusNotFound:
code = gcode.CodeNotFound
case http.StatusForbidden:
code = gcode.CodeNotAuthorized
default:
code = gcode.CodeUnknown
}
// It creates error as it can be retrieved by other middlewares.
err = gerror.NewCode(code, msg)
r.SetError(err)
} else {
code = gcode.CodeOK
}
}
g.Log().Print(nil, r.Response.Status, r.URL.Path, err)
r.Response.WriteJson(DefaultHandlerResponse{
Code: code.Code(),
Message: msg,
Data: res,
})
}