gin通用响应封装
# Gin 通用响应封装
package handlers
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"sync"
)
type JSONResult struct {
Message string `json:"message"`
Code string `json:"code"`
Result interface{} `json:"result"`
}
func NewJSONResult(message string, code string, result interface{}) *JSONResult {
return &JSONResult{Message: message, Code: code, Result: result}
}
var ResultPool *sync.Pool
func init() {
ResultPool = &sync.Pool{
// 定义池子里放什么: 初始化一个 JSONResult 实例
// 可以复用已经使用过的对象
// 减少对象的创建和回收的时间
New: func() interface{} {
return NewJSONResult("", "", nil)
},
}
}
type ResultFunc func(message, code string, result interface{}) func(output Output)
// Output 决定返回的函数类型 对应下面的 Ok 和 Error
type Output func(c *gin.Context, v interface{})
// R 通用响应内容封装
func R(c *gin.Context) ResultFunc {
return func(message, code string, result interface{}) func(output Output) {
r := ResultPool.Get().(*JSONResult)
// 取出数据后通过 Put 放回去
defer ResultPool.Put(r)
r.Message = message
r.Code = code
r.Result = result
c.JSON(http.StatusOK, r)
return func(output Output) {
output(c, r)
}
}
}
func Ok(c *gin.Context, v interface{}) {
c.JSON(http.StatusOK, v)
}
func Error(c *gin.Context, v interface{}) {
c.JSON(http.StatusBadRequest, v)
}
func Ok2String(c *gin.Context, v interface{}) {
c.String(http.StatusOK, fmt.Sprintf("%v", v))
}
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
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
编辑 (opens new window)
上次更新: 2022/09/04, 12:06:50