-
Notifications
You must be signed in to change notification settings - Fork 145
Open
Description
现在定义了一个标准的返回数据格式如下
package utils
import (
"context"
"fmt"
"github.com/kuangshp/go-utils/k"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"net/http"
)
type Response struct {
Code int64 `json:"code"`
Message string `json:"message"`
Result interface{} `json:"result,omitempty"`
}
func Success(data interface{}) *Response {
return &Response{
Code: 0,
Message: "请求成功",
Result: data,
}
}
func Fail(err string) *Response {
return &Response{
Code: 1,
Message: err,
Result: nil,
}
}
func OriginalResponse(code int64, message string, data interface{}) *Response {
return &Response{
Code: code,
Message: message,
Result: data,
}
}
func OkHandler(_ context.Context, v interface{}) any {
return Success(v)
}
func ErrHandler(name string) func(ctx context.Context, err error) (int, any) {
return func(ctx context.Context, err error) (int, any) {
fmt.Println(err, "错误信息")
causeErr := errors.Cause(err)
fmt.Println(causeErr, "111-->")
var errMessage = err.Error()
if k.IsContains([]string{"请传递token", "token过期"}, errMessage) {
return http.StatusOK, OriginalResponse(10024, errMessage, nil)
}
// 翻译错误
translatorError := TranslatorError(err)
if translatorError != "" {
errMessage = translatorError
}
// 日志记录
logx.WithContext(ctx).Errorf("【%s】 err %v", name, errMessage)
return http.StatusOK, Fail(errMessage)
}
}在全局使用了拦截器返回数据
// 使用拦截器
httpx.SetOkHandler(utils.OkHandler)
httpx.SetErrorHandlerCtx(utils.ErrHandler(c.Name))在api文件中直接定义
type MenusResp {
ID int64 `json:"id"` // 主键id
Title string `json:"title"` // 名称:按钮标题,或菜单标题
URL string `json:"url"` // 按钮请求url,或菜单路由
Icon string `json:"icon"` // 菜单小图标
ResourcesType int64 `json:"resourcesType"` // 类型:0表示目录,1表示菜单,2表示接口
IsCache int64 `json:"isCache"` // 是否缓存:0表示缓存:1不缓存
IsHidden int64 `json:"isHidden"` // 是否隐藏:0表示不隐藏,1表示隐藏
IsLink int64 `json:"isLink"` // 是否为外部链接:0表示不是,1表示是
ParentID int64 `json:"parentId"` // 上一级id
Sort int64 `json:"sort"` // 菜单,或按钮排序
UniqueKey string `json:"uniqueKey"` // 权限唯一标识
}
@server(
prefix: api/v1/admin/menu
group: menus
middleware: AuthMiddleware,LoggerMiddleWare
)
service admin-api {
@doc "获取用户菜单"
@handler GetMenusApi
get / returns ([]MenusResp)
}希望生成的文档中带上code,message,reuslt为api里面定义的内容体,要如何来实现呢
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels