From 0920b7680bbc5e97f0a52b4763ed76e8618af623 Mon Sep 17 00:00:00 2001 From: wangfuduo Date: Wed, 8 Jul 2026 17:47:13 +0800 Subject: [PATCH] refactor: response --- app/api/response/response.go | 66 +++++++++++++++--------------------- 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/app/api/response/response.go b/app/api/response/response.go index 9d291e1..b71f614 100644 --- a/app/api/response/response.go +++ b/app/api/response/response.go @@ -3,15 +3,17 @@ package response import ( "fmt" "time" + "twin-api/base/config" "github.com/gin-gonic/gin" ) +const defaultTitle = "温馨提示" + type Button struct { - Color string `json:"-"` - Text string `json:"text"` - Url string `json:"url"` - Type string `json:"type"` + Text string `json:"text"` + Url string `json:"url"` + Type string `json:"type"` } type Window struct { @@ -25,7 +27,6 @@ type Data struct { } type Response struct { - ctx *gin.Context Code int `json:"code"` Msg string `json:"message"` Trace string `json:"trace"` @@ -33,41 +34,25 @@ type Response struct { } func New(ctx *gin.Context, code int, message string) *Response { - var trace string - var ok bool - if ctx.Keys != nil { - if trace, ok = ctx.Keys["req_id"].(string); !ok { - trace = fmt.Sprintf("%d", time.Now().UnixMicro()) - } + trace, ok := ctx.Keys[config.TraceId].(string) + if !ok { + trace = fmt.Sprintf("%d", time.Now().UnixMicro()) } - response := new(Response) - response.Code = code - response.Msg = message - response.Trace = trace - response.Data.Buttons = make([]*Button, 0) - response.Data.Window = Window{Title: "温馨提示", Close: true} - return response + return &Response{ + Code: code, + Msg: message, + Trace: trace, + Data: Data{ + Buttons: make([]*Button, 0), + Window: Window{Title: defaultTitle, Close: true}, + }, + } } +// Button 用传入的一组按钮替换掉原有的全部按钮 func (r *Response) Button(b ...*Button) *Response { - if len(b) > 1 { - r.Data.Buttons = append(r.Data.Buttons[:0], b...) - } - - if len(b) == 1 { - r.Data.Buttons = append(r.Data.Buttons, b...) - } - - return r -} - -func (r *Response) Window(win *Window) *Response { - if win.Title != "" { - r.Data.Window.Title = win.Title - } - - r.Data.Window.Close = win.Close + r.Data.Buttons = append(r.Data.Buttons[:0], b...) return r } @@ -76,9 +61,12 @@ func (r *Response) Message(message string) *Response { return r } -func (r *Response) Title(t string) *Response { r.Data.Window.Title = t; return r } -func (r *Response) Closable(b bool) *Response { r.Data.Window.Close = b; return r } -func (r *Response) AddButton(text, url, typ string) *Response { - r.Data.Buttons = append(r.Data.Buttons, &Button{Text: text, Url: url, Type: typ}) +func (r *Response) Title(t string) *Response { + r.Data.Window.Title = t + return r +} + +func (r *Response) Closable(b bool) *Response { + r.Data.Window.Close = b return r }