You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tool/services/response/response.go

39 lines
877 B

package response
import "encoding/json"
// 返回码
const (
Success = 0
Fail = -1
)
// Response 统一响应结构
type Response[T any] struct {
Errcode int `json:"errcode"` // 返回码
Errmsg string `json:"errmsg"` // 对返回码的文本描述内容
Data T `json:"data"` // 返回数据
}
// NewResponse 创建响应
func NewResponse[T any](errcode int, errmsg string, data T) Response[T] {
return Response[T]{Errcode: errcode, Errmsg: errmsg, Data: data}
}
// SuccessResponse 成功返回
func SuccessResponse[T any](data T) Response[T] {
return NewResponse[T](Success, "success", data)
}
// FailResponse 失败返回
func FailResponse[T any](errmsg string) Response[T] {
var data T
return NewResponse[T](Fail, errmsg, data)
}
// Bytes 将响应转换为[]byte
func (r Response[T]) Bytes() []byte {
b, _ := json.Marshal(r)
return b
}