-
Notifications
You must be signed in to change notification settings - Fork 17
/
JsonFormatMiddleware.go
66 lines (57 loc) · 1.69 KB
/
JsonFormatMiddleware.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
package Middleware
import (
"bytes"
"encoding/json"
"fmt"
"github.com/duolabmeng6/goefun/egin/jsonconv"
"github.com/gin-gonic/gin"
"strings"
)
type ResponseWriterWrapper struct {
gin.ResponseWriter
Body *bytes.Buffer // 缓存
CamelCase bool // 真驼峰 假下划线
}
func (w ResponseWriterWrapper) Write(b []byte) (int, error) {
//如果是json格式
if strings.Contains(w.Header().Get("Content-Type"), "application/json") {
var u interface{}
err := json.Unmarshal(b, &u)
if err != nil {
fmt.Sprintf("json.Unmarshal error %v", err)
return 0, err
}
var marshal []byte
if w.CamelCase {
marshal, _ = json.Marshal(jsonconv.JsonCamelCase{Value: u})
} else {
marshal, _ = json.Marshal(jsonconv.JsonSnakeCase{Value: u})
}
b = []byte(fmt.Sprintf("%s", marshal))
}
w.Body.Write(b)
return w.ResponseWriter.Write(b)
}
func (w ResponseWriterWrapper) WriteString(s string) (int, error) {
w.Body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
// JsonFormatMiddleware
//
// 自动将json数据重新转化为驼峰或者下划线
//
// 参数1 CamelCase true 驼峰 false 下划线
//
// 参数2 UrlPrefix 前缀 作用的url前缀
func JsonFormatMiddleware(CamelCase bool, UrlPrefix string) gin.HandlerFunc {
// CamelCase true 驼峰 false 下划线
return func(ctx *gin.Context) {
//检查 UrlPrefix 前缀是否匹配 如果匹配则修改json返回格式
print("ctx.Request.URL.Path=", ctx.Request.URL.Path, " UrlPrefix=", UrlPrefix, "\n")
if strings.HasPrefix(ctx.Request.URL.Path, UrlPrefix) {
w := &ResponseWriterWrapper{Body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer, CamelCase: CamelCase}
ctx.Writer = w
}
ctx.Next()
}
}