twin-api/app/api/response/response.go

85 lines
1.7 KiB
Go

package response
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
)
type Button struct {
Color string `json:"-"`
Text string `json:"text"`
Url string `json:"url"`
Type string `json:"type"`
}
type Window struct {
Title string `json:"title"`
Close bool `json:"close"`
}
type Data struct {
Buttons []*Button `json:"buttons"`
Window Window `json:"window"`
}
type Response struct {
ctx *gin.Context
Code int `json:"code"`
Msg string `json:"message"`
Trace string `json:"trace"`
Data Data `json:"data"`
}
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())
}
}
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
}
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
}
func (r *Response) Message(message string) *Response {
r.Msg = message
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})
return r
}