-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttp_utils.go
71 lines (59 loc) · 1.55 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
package grpcx
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/labstack/echo"
)
// JSONResult json result
type JSONResult struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
// NewJSONBodyHTTPHandle returns a http handle JSON body
func NewJSONBodyHTTPHandle(factory func() interface{}, handler func(interface{}) (*JSONResult, error)) func(echo.Context) error {
return func(ctx echo.Context) error {
value := factory()
err := ReadJSONFromBody(ctx, value)
if err != nil {
return ctx.JSON(http.StatusBadRequest, &JSONResult{
Data: err.Error(),
})
}
result, err := handler(value)
if err != nil {
return ctx.NoContent(http.StatusInternalServerError)
}
return ctx.JSON(http.StatusOK, result)
}
}
// NewGetHTTPHandle return get http handle
func NewGetHTTPHandle(factory func(echo.Context) (interface{}, error), handler func(interface{}) (*JSONResult, error)) func(echo.Context) error {
return func(ctx echo.Context) error {
value, err := factory(ctx)
if err != nil {
return ctx.JSON(http.StatusBadRequest, &JSONResult{
Data: err.Error(),
})
}
result, err := handler(value)
if err != nil {
return ctx.NoContent(http.StatusInternalServerError)
}
return ctx.JSON(http.StatusOK, result)
}
}
// ReadJSONFromBody read json body
func ReadJSONFromBody(ctx echo.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
}