-
Notifications
You must be signed in to change notification settings - Fork 0
/
hres_json.go
104 lines (88 loc) · 2.93 KB
/
hres_json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package hresp
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
// 自定义响应枚举
const (
SUCCESS = 200 // 操作成功
FAIL = 201 // 操作失败
SERVER_ERROR = 500 // 服务器内部错误
BUSINESS_ERROR = 501 // 通用业务异常
)
// JsonResponse 数据返回通用json数据结构
type JsonResponse struct {
Code int `json:"code"` // 状态码(200:操作成功,201:操作失败,500:服务器内部错误,501:通用业务异常)
Message string `json:"message"` // 提示信息
Data interface{} `json:"data"` // 响应数据
Exception interface{} `json:"exception"` // 异常信息
}
// result 内部调用
func result(r *ghttp.Request, code int, message string, data interface{}, exception interface{}) {
if err := r.Response.WriteJson(JsonResponse{
code,
message,
data,
exception,
}); err != nil {
g.Log().Error(err)
}
// 仅退出当前执行的逻辑方法
r.Exit()
}
// Ok 操作成功
func Ok(r *ghttp.Request) {
result(r, SUCCESS, "操作成功", map[string]interface{}{}, nil)
}
// OkWithMsg 操作成功(自定义消息)
func OkWithMsg(r *ghttp.Request, message string) {
result(r, SUCCESS, message, map[string]interface{}{}, nil)
}
// OkWithData 操作成功(自定义数据)
func OkWithData(r *ghttp.Request, data interface{}) {
result(r, SUCCESS, "操作成功", data, nil)
}
// OkWithDataAndMsg 操作成功(自定义消息和数据)
func OkWithDataAndMsg(r *ghttp.Request, message string, data interface{}) {
result(r, SUCCESS, message, data, nil)
}
// Fail 操作失败
func Fail(r *ghttp.Request) {
result(r, FAIL, "操作失败", map[string]interface{}{}, nil)
}
// FailWithMsg 操作失败(自定义消息)
func FailWithMsg(r *ghttp.Request, message string) {
result(r, FAIL, message, map[string]interface{}{}, nil)
}
// FailWithEx 操作失败(自定义异常信息)
func FailWithEx(r *ghttp.Request, exception interface{}) {
result(r, FAIL, "操作失败", nil, exception)
}
// FailWithCodeAndMsg 操作失败(自定义错误码和消息)
func FailWithCodeAndMsg(r *ghttp.Request, code int, message string) {
result(r, code, message, nil, nil)
}
// FailWithCodeMsgAndEx 操作失败(自定义错误码、消息、异常信息)
func FailWithCodeMsgAndEx(r *ghttp.Request, code int, message string, exception interface{}) {
result(r, code, message, nil, exception)
}
// Json 标准返回结果数据结构封装
func Json(r *ghttp.Request, code int, message string, data ...interface{}) {
responseData := interface{}(nil)
if len(data) > 0 {
responseData = data[0]
}
err := r.Response.WriteJson(JsonResponse{
Code: code,
Message: message,
Data: responseData,
})
if err != nil {
g.Log().Error(err)
}
}
// JsonExit 返回json数据并退出当前http执行函数
func JsonExit(r *ghttp.Request, err int, msg string, data ...interface{}) {
Json(r, err, msg, data...)
r.Exit()
}