yuleduiPay/middle/middle.go

70 lines
1.6 KiB
Go

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()
}
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) {
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,
})
}