You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/zero/statusz/handler.go

42 lines
1.2 KiB
Go

1 year ago
package statusz
import (
"git.noahlan.cn/noahlan/ntool-biz/core/i18n"
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
"github.com/zeromicro/go-zero/rest/httpx"
"net/http"
)
// ResponseHandler API执行结果处理统一返回值类型与结构
func ResponseHandler(req *http.Request, w http.ResponseWriter, trans bool, resp any, err error) {
if err == nil {
r := nstatus.NewResultWithData(http.StatusOK, msg.Success, nstatus.CommonResult, resp)
1 year ago
if trans {
r.Msg = i18n.Trans(req.Context(), r.Msg)
}
httpx.WriteJson(w, http.StatusOK, r)
1 year ago
return
}
result := nstatus.ConvertErr(err)
if result == nil {
// 不可能发生此情况,这里处理是以防万一
result = nstatus.NewResult(http.StatusOK, msg.Success, nstatus.CommonResult)
1 year ago
}
result.Data = resp
if trans {
result.Msg = i18n.Trans(req.Context(), result.Msg)
}
c := http.StatusInternalServerError
if result.Type == nstatus.ApiErr {
// API错误按照Result内的code返回若code不是标准http错误则按照500返回
c = result.Code
if c > http.StatusNetworkAuthenticationRequired {
c = http.StatusInternalServerError
}
1 year ago
}
// 其它错误统一按照500返回
1 year ago
httpx.WriteJson(w, c, result)
}