1 Star 0 Fork 0

xlizy/common-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
response.go 2.81 KB
一键复制 编辑 原始数据 按行查看 历史
xlizy 提交于 2024-04-25 10:21 . save
package response
import (
"gitee.com/xlizy/common-go/base/const"
"gitee.com/xlizy/common-go/base/const/threadlocal"
"gitee.com/xlizy/common-go/base/enums/common_error"
"gitee.com/xlizy/common-go/utils/zlog"
"reflect"
"time"
)
type Response struct {
Success bool `json:"success"`
Code int32 `json:"code"`
Msg string `json:"msg,omitempty"`
ResponseTime string `json:"responseTime,omitempty"`
TraceId string `json:"traceId,omitempty"`
Data any `json:"data,omitempty"`
Extend map[string]string `json:"extend,omitempty"`
}
type PageResponse struct {
Total int64 `json:"total"`
Data any `json:"data"`
PageNum int `json:"pageNum"`
PageSize int `json:"pageSize"`
Pages int `json:"pages"`
Size int `json:"size"`
}
func Succ() *Response {
return &Response{Success: true, Code: 0, Msg: "", ResponseTime: time.Now().Format(constant.DataFormat), TraceId: threadlocal.GetTraceId()}
}
func Success(msg string, data any) *Response {
return &Response{Success: true, Code: 0, Msg: msg, ResponseTime: time.Now().Format(constant.DataFormat), TraceId: threadlocal.GetTraceId(), Data: data}
}
func SuccessCus(msg string, data any, extend map[string]string) *Response {
return &Response{Success: true, Code: 0, Msg: msg, ResponseTime: time.Now().Format(constant.DataFormat), TraceId: threadlocal.GetTraceId(), Data: data, Extend: extend}
}
func ErrorCus(code int32, msg string, data any) *Response {
return &Response{Success: false, Code: code, Msg: msg, ResponseTime: time.Now().Format(constant.DataFormat), TraceId: threadlocal.GetTraceId(), Data: data}
}
func Error(errType any, data any) (res *Response) {
res = &Response{Success: false, Code: common_error.SYS_ERR_ENUM_ERROR.Code(), Msg: common_error.SYS_ERR_ENUM_ERROR.Des(), ResponseTime: time.Now().Format(constant.DataFormat), TraceId: threadlocal.GetTraceId(), Data: data}
defer func(r *Response) {
err := recover() // recover()内置函数,可以捕获到异常
if err != nil { //说明捕获到错误
}
}(res)
code := reflect.ValueOf(errType).MethodByName("Code").Call(nil)[0]
des := reflect.ValueOf(errType).MethodByName("Des").Call(nil)[0]
res.Code = int32(code.Int())
res.Msg = des.String()
return res
}
func RpcError(err error) *Response {
zlog.Info("调用rpc服务异常:{}", err.Error())
return &Response{
Success: false,
Code: common_error.RPC_EXECUTE_ERROR.Code(),
Msg: common_error.RPC_EXECUTE_ERROR.Des(),
ResponseTime: time.Now().Format(constant.DataFormat),
TraceId: threadlocal.GetTraceId(),
}
}
func Page(total int64, data any, pageNum, pageSize, pages, size int) *PageResponse {
return &PageResponse{Total: total, Data: data, PageNum: pageNum, PageSize: pageSize, Pages: pages, Size: size}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xlizy/common-go.git
git@gitee.com:xlizy/common-go.git
xlizy
common-go
common-go
v0.2.11

搜索帮助

0d507c66 1850385 C8b1a773 1850385