51 lines
947 B
Go
51 lines
947 B
Go
|
|
package response
|
||
|
|
|
||
|
|
// Response 统一响应结构
|
||
|
|
type Response struct {
|
||
|
|
Code int `json:"code"`
|
||
|
|
Message string `json:"message"`
|
||
|
|
Data interface{} `json:"data,omitempty"`
|
||
|
|
}
|
||
|
|
|
||
|
|
// Success 成功响应
|
||
|
|
func Success(data interface{}) *Response {
|
||
|
|
return &Response{
|
||
|
|
Code: 0,
|
||
|
|
Message: "success",
|
||
|
|
Data: data,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Error 错误响应
|
||
|
|
func Error(message string) *Response {
|
||
|
|
return &Response{
|
||
|
|
Code: -1,
|
||
|
|
Message: message,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// ErrorWithCode 带错误码的错误响应
|
||
|
|
func ErrorWithCode(code int, message string) *Response {
|
||
|
|
return &Response{
|
||
|
|
Code: code,
|
||
|
|
Message: message,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// WithData 带扩展数据的成功响应
|
||
|
|
func WithData(data interface{}, extra map[string]interface{}) *Response {
|
||
|
|
payload, ok := data.(map[string]interface{})
|
||
|
|
if !ok {
|
||
|
|
payload = map[string]interface{}{
|
||
|
|
"items": data,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
for k, v := range extra {
|
||
|
|
payload[k] = v
|
||
|
|
}
|
||
|
|
|
||
|
|
resp := Success(payload)
|
||
|
|
return resp
|
||
|
|
}
|