refactor: response
This commit is contained in:
parent
11c5ab5094
commit
0920b7680b
|
|
@ -3,12 +3,14 @@ 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"`
|
||||
|
|
@ -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, ok := ctx.Keys[config.TraceId].(string)
|
||||
if !ok {
|
||||
trace = fmt.Sprintf("%d", time.Now().UnixMicro())
|
||||
}
|
||||
|
||||
return &Response{
|
||||
Code: code,
|
||||
Msg: message,
|
||||
Trace: trace,
|
||||
Data: Data{
|
||||
Buttons: make([]*Button, 0),
|
||||
Window: Window{Title: defaultTitle, Close: true},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
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
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue