/
ginplus.go
146 lines (127 loc) · 3.39 KB
/
ginplus.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
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
136
137
138
139
140
141
142
143
144
145
146
package ginplus
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/ops-cn/common/errors"
"github.com/ops-cn/common/logger"
"github.com/ops-cn/common/schema"
"github.com/ops-cn/common/util"
)
// 定义上下文中的键
const (
prefix = "gin-admin"
UserIDKey = prefix + "/user-id"
ReqBodyKey = prefix + "/req-body"
ResBodyKey = prefix + "/res-body"
LoggerReqBodyKey = prefix + "/logger-req-body"
)
// GetToken 获取用户令牌
func GetToken(c *gin.Context) string {
var token string
auth := c.GetHeader("Authorization")
prefix := "Bearer "
if auth != "" && strings.HasPrefix(auth, prefix) {
token = auth[len(prefix):]
}
return token
}
// GetUserID 获取用户ID
func GetUserID(c *gin.Context) string {
return c.GetString(UserIDKey)
}
// SetUserID 设定用户ID
func SetUserID(c *gin.Context, userID string) {
c.Set(UserIDKey, userID)
}
// GetBody Get request body
func GetBody(c *gin.Context) []byte {
if v, ok := c.Get(ReqBodyKey); ok {
if b, ok := v.([]byte); ok {
return b
}
}
return nil
}
// ParseJSON 解析请求JSON
func ParseJSON(c *gin.Context, obj interface{}) error {
if err := c.ShouldBindJSON(obj); err != nil {
return errors.Wrap400Response(err, fmt.Sprintf("解析请求参数发生错误 - %s", err.Error()))
}
return nil
}
// ParseQuery 解析Query参数
func ParseQuery(c *gin.Context, obj interface{}) error {
if err := c.ShouldBindQuery(obj); err != nil {
return errors.Wrap400Response(err, fmt.Sprintf("解析请求参数发生错误 - %s", err.Error()))
}
return nil
}
// ParseForm 解析Form请求
func ParseForm(c *gin.Context, obj interface{}) error {
if err := c.ShouldBindWith(obj, binding.Form); err != nil {
return errors.Wrap400Response(err, fmt.Sprintf("解析请求参数发生错误 - %s", err.Error()))
}
return nil
}
// ResOK 响应OK
func ResOK(c *gin.Context) {
ResSuccess(c, schema.StatusResult{Status: schema.OKStatus})
}
// ResList 响应列表数据
func ResList(c *gin.Context, v interface{}) {
ResSuccess(c, schema.ListResult{List: v})
}
// ResPage 响应分页数据
func ResPage(c *gin.Context, v interface{}, pr *schema.PaginationResult) {
list := schema.ListResult{
List: v,
Pagination: pr,
}
ResSuccess(c, list)
}
// ResSuccess 响应成功
func ResSuccess(c *gin.Context, v interface{}) {
ResJSON(c, http.StatusOK, v)
}
// ResJSON 响应JSON数据
func ResJSON(c *gin.Context, status int, v interface{}) {
buf, err := util.JSONMarshal(v)
if err != nil {
panic(err)
}
c.Set(ResBodyKey, buf)
c.Data(status, "application/json; charset=utf-8", buf)
c.Abort()
}
// ResError 响应错误
func ResError(c *gin.Context, err error, status ...int) {
ctx := c.Request.Context()
var res *errors.ResponseError
if err != nil {
if e, ok := err.(*errors.ResponseError); ok {
res = e
} else {
res = errors.UnWrapResponse(errors.Wrap500Response(err, "服务器错误"))
}
} else {
res = errors.UnWrapResponse(errors.ErrInternalServer)
}
if len(status) > 0 {
res.StatusCode = status[0]
}
if err := res.ERR; err != nil {
if status := res.StatusCode; status >= 400 && status < 500 {
logger.StartSpan(ctx).Warnf(err.Error())
} else if status >= 500 {
logger.ErrorStack(ctx, err)
}
}
eitem := schema.ErrorItem{
Code: res.Code,
Message: res.Message,
}
ResJSON(c, res.StatusCode, schema.ErrorResult{Error: eitem})
}