forked from fagongzi/grpcx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_utils.go
86 lines (74 loc) · 1.77 KB
/
http_utils.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
package grpcx
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
)
// JSONResult json result
type JSONResult struct {
Code int `json:"code"`
Data interface{} `json:"data,omitempty"`
Message string `json:"msg,omitempty"`
}
// NewJSONBodyHTTPHandle returns a http handle JSON body
func NewJSONBodyHTTPHandle(factory func() interface{}, handler func(interface{}) (*JSONResult, error)) func(c *gin.Context) {
return func(c *gin.Context) {
value := factory()
err := ReadJSONFromBody(c, value)
if err != nil {
c.JSON(http.StatusOK, &JSONResult{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
result, err := handler(value)
if err != nil {
c.JSON(http.StatusOK, &JSONResult{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, result)
return
}
}
// NewGetHTTPHandle return get http handle
func NewGetHTTPHandle(factory func(*gin.Context) (interface{}, error), handler func(interface{}) (*JSONResult, error)) func(c *gin.Context) {
return func(c *gin.Context) {
value, err := factory(c)
if err != nil {
c.JSON(http.StatusOK, &JSONResult{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
result, err := handler(value)
if err != nil {
c.JSON(http.StatusOK, &JSONResult{
Code: http.StatusInternalServerError,
Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, result)
return
}
}
// ReadJSONFromBody read json body
func ReadJSONFromBody(ctx *gin.Context, value interface{}) error {
data, err := ioutil.ReadAll(ctx.Request.Body)
if err != nil {
return err
}
if len(data) > 0 {
err = json.Unmarshal(data, value)
if err != nil {
return err
}
}
return nil
}