1 Star 0 Fork 0

瑞哥 / jk

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Resp.go 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
Your Name 提交于 2023-11-24 11:30 . init
package jk
import (
"encoding/json"
"net/http"
)
type Resp interface {
SetCode(code int)
SetMsg(msg string)
SetData(data any)
SetOther(other any)
ToJson() []byte
Value() any //返回可以JSON编码的对象
CodeValue() (int, any) //返回http状态码code和可以JSON编码的对象
CodeValueOK() (int, any) //返回http状态码200和可以JSON编码的对象
}
// NewResp 创建一个标准的响应体结构
func NewResp(code int, msg string, data any, other any) Resp {
return &stdResp{
Code: code,
Msg: msg,
Data: stdRespData{Data: data, Other: other},
}
}
// NewRespOK 创建一个标准的响应体结构,默认code = 200
func NewRespOK(dataOther ...any) Resp {
var rt = &stdResp{Code: http.StatusOK}
length := len(dataOther)
switch length {
case 0:
case 1:
rt.Data.Data = dataOther[0]
case 2:
rt.Data.Data = dataOther[0]
rt.Data.Other = dataOther[1]
default:
rt.Data.Data = dataOther[0]
rt.Data.Other = dataOther[1:]
}
return rt
}
// NewRespErr 创建一个标准的响应体结构,默认无Data
func NewRespErr(code int, msg string) Resp {
return &stdResp{
Code: code,
Msg: msg,
}
}
type stdResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data stdRespData `json:"data"`
}
type stdRespData struct {
Data any `json:"data"`
Other any `json:"other"`
}
func (r *stdResp) SetCode(code int) {
r.Code = code
}
func (r *stdResp) SetMsg(msg string) {
r.Msg = msg
}
func (r *stdResp) SetData(data any) {
r.Data.Data = data
}
func (r *stdResp) SetOther(other any) {
r.Data.Other = other
}
func (r *stdResp) ToJson() []byte {
marshal, _ := json.Marshal(r)
return marshal
}
func (r *stdResp) Value() any {
return r
}
func (r *stdResp) CodeValue() (int, any) {
return r.Code, r
}
func (r *stdResp) CodeValueOK() (int, any) {
return http.StatusOK, r
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ruige_fun/jk.git
git@gitee.com:ruige_fun/jk.git
ruige_fun
jk
jk
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891