-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
76 lines (66 loc) · 1.74 KB
/
message.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
package go_cover_support
import "net/http"
type ResponseMessage struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
type ResponseContext interface {
JSON(code int, obj interface{})
AbortWithStatusJSON(code int, jsonObj interface{})
}
func Msg(data ...interface{}) ResponseMessage {
result := ResponseMessage{
Code: http.StatusOK,
Message: "ok",
Data: nil,
}
count := len(data)
if count > 0 {
result.Data = data[0]
}
if count > 1 {
if message, ok := data[1].(string); ok && message != "" {
result.Message = message
}
}
if count > 2 {
if code, ok := data[2].(int); ok && code > 0 {
result.Code = code
}
}
return result
}
func Succeed(ctx ResponseContext, data ...interface{}) {
var newData interface{}
newMessage := ""
count := len(data)
if count > 0 {
newData = data[0]
}
if count > 1 {
if message, ok := data[1].(string); ok {
newMessage = message
}
}
ctx.JSON(http.StatusOK, Msg(newData, newMessage, http.StatusOK))
}
func Error(ctx ResponseContext, code int, err error, data ...interface{}) {
var newData interface{}
if len(data) > 0 {
newData = data[0]
}
ctx.AbortWithStatusJSON(http.StatusOK, Msg(newData, err.Error(), code))
}
func ErrorBadRequest(ctx ResponseContext, err error, data ...interface{}) {
Error(ctx, http.StatusBadRequest, err, data)
}
func ErrorInternalServerError(ctx ResponseContext, err error, data ...interface{}) {
Error(ctx, http.StatusInternalServerError, err, data)
}
func ErrorUnauthorized(ctx ResponseContext, err error, data ...interface{}) {
Error(ctx, http.StatusUnauthorized, err, data)
}
func ErrorNotFound(ctx ResponseContext, err error, data ...interface{}) {
Error(ctx, http.StatusNotFound, err, data)
}