-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathmessage.go
More file actions
135 lines (123 loc) · 2.44 KB
/
Copy pathmessage.go
File metadata and controls
135 lines (123 loc) · 2.44 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package quark
type Message struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
Url string `json:"url,omitempty"`
}
type CodeMap struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
var (
StatusOk = 200 // 执行成功
StatusUnauthorized = 401 // 未授权
StatusForbidden = 403 // 无权限
StatusError = 10001 // 自定义错误信息
StatusParamError = 10002 // 参数错误
)
var CodeMaps = []*CodeMap{
{
Code: StatusOk,
Msg: "ok",
},
{
Code: StatusError,
Msg: "Internal Server Error",
},
{
Code: StatusParamError,
Msg: "Param Error",
},
{
Code: StatusUnauthorized,
Msg: "Unauthorized",
},
{
Code: StatusForbidden,
Msg: "Forbidden",
},
}
// 根据code获取错误信息
func GetMsgByCode(code int) string {
for _, v := range CodeMaps {
if v.Code == code {
return v.Msg
}
}
return ""
}
// 返回正确信息
func Success(message string, data interface{}) *Message {
return &Message{
Code: StatusOk,
Msg: message,
Data: data,
}
}
// 返回错误信息,Error("内部服务调用异常") | Error("错误", map[string]interface{}{"title":"标题"})
func Error(params ...interface{}) *Message {
var (
code = StatusError
msg = ""
data interface{}
)
if len(params) == 1 {
msg = params[0].(string)
}
if len(params) == 2 {
msg = params[0].(string)
data = params[1]
}
return &Message{
Code: code,
Msg: msg,
Data: data,
}
}
// 返回错误信息,ErrorByCode(10001) | ErrorByCode(10001, map[string]interface{}{"title":"标题"})
func ErrorByCode(params ...interface{}) *Message {
var (
code = StatusError
msg = ""
data interface{}
)
if len(params) == 1 {
code = params[0].(int)
}
if len(params) == 2 {
code = params[0].(int)
data = params[1]
}
msg = GetMsgByCode(code)
return &Message{
Code: code,
Msg: msg,
Data: data,
}
}
// 输出模版引擎URL跳转,RedirectTo("/home/index") | RedirectTo("成功", "/home/index") | RedirectTo("失败", "/home/index", 10001)
func RedirectTo(params ...interface{}) *Message {
var (
msg = ""
url = ""
code = 200
)
if len(params) == 1 {
url = params[0].(string)
}
if len(params) == 2 {
msg = params[0].(string)
url = params[1].(string)
}
if len(params) >= 3 {
msg = params[0].(string)
url = params[1].(string)
code = params[2].(int)
}
return &Message{
Code: code,
Msg: msg,
Url: url,
}
}