refactor: response

This commit is contained in:
wangfuduo 2026-07-08 17:47:13 +08:00
parent 11c5ab5094
commit 0920b7680b
1 changed files with 27 additions and 39 deletions

View File

@ -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
}