-
Notifications
You must be signed in to change notification settings - Fork 5
/
response.go
89 lines (71 loc) · 1.73 KB
/
response.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
package serialize
import (
"net/http"
"sync"
)
type CodeMessager func(int) string
var cm CodeMessager
// SetCodeMessager 设置一个CodeMessager,该函数可以从code获取message
func SetCodeMessager(messager CodeMessager) {
cm = messager
}
type resResult struct {
Data interface{} `json:"data"`
Status int `json:"status"`
Message string `json:"message"`
}
type Response struct {
HttpStatus int
R resResult
}
const (
SuccessCode = iota
FailCode
ErrorCode
)
var pool = sync.Pool{
New: func() interface{} {
return &Response{}
},
}
func PutResponse(resp *Response) {
pool.Put(resp)
}
func NewResponse(status, code int, data interface{}, message string) *Response {
res := pool.Get().(*Response)
res.HttpStatus = status
res.R.Status = code
res.R.Data = data
res.R.Message = message
return res
}
func Ok() *Response {
return NewResponse(http.StatusOK, SuccessCode, nil, "success")
}
func OkData(data interface{}) *Response {
return NewResponse(http.StatusOK, SuccessCode, data, "success")
}
func OkCode(code int) *Response {
if cm != nil {
return NewResponse(http.StatusOK, code, nil, cm(code))
}
return NewResponse(http.StatusOK, code, nil, "success")
}
func OkCodeData(code int, data interface{}) *Response {
if cm != nil {
return NewResponse(http.StatusOK, code, data, cm(code))
}
return NewResponse(http.StatusOK, code, data, "success")
}
func Fail(code int) *Response {
return FailData(code, nil)
}
func FailData(code int, data interface{}) *Response {
if cm != nil {
return NewResponse(http.StatusOK, code, data, cm(code))
}
return NewResponse(http.StatusOK, FailCode, data, "failed")
}
func Error(status int) *Response {
return NewResponse(status, ErrorCode, nil, "error")
}