|
| 1 | +package grpcx |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io/ioutil" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "github.com/labstack/echo" |
| 9 | +) |
| 10 | + |
| 11 | +// JSONResult json result |
| 12 | +type JSONResult struct { |
| 13 | + Code int `json:"code"` |
| 14 | + Data interface{} `json:"data"` |
| 15 | +} |
| 16 | + |
| 17 | +// NewJSONBodyHTTPHandle returns a http handle JSON body |
| 18 | +func NewJSONBodyHTTPHandle(factory func() interface{}, handler func(interface{}) (*JSONResult, error)) func(echo.Context) error { |
| 19 | + return func(ctx echo.Context) error { |
| 20 | + value := factory() |
| 21 | + err := ReadJSONFromBody(ctx, value) |
| 22 | + if err != nil { |
| 23 | + return ctx.NoContent(http.StatusBadRequest) |
| 24 | + } |
| 25 | + |
| 26 | + result, err := handler(value) |
| 27 | + if err != nil { |
| 28 | + return ctx.NoContent(http.StatusInternalServerError) |
| 29 | + } |
| 30 | + |
| 31 | + return ctx.JSON(http.StatusOK, result) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +// NewGetHTTPHandle return get http handle |
| 36 | +func NewGetHTTPHandle(factory func(echo.Context) (interface{}, error), handler func(interface{}) (*JSONResult, error)) func(echo.Context) error { |
| 37 | + return func(ctx echo.Context) error { |
| 38 | + value, err := factory(ctx) |
| 39 | + if err != nil { |
| 40 | + return ctx.NoContent(http.StatusBadRequest) |
| 41 | + } |
| 42 | + |
| 43 | + result, err := handler(value) |
| 44 | + if err != nil { |
| 45 | + return ctx.NoContent(http.StatusInternalServerError) |
| 46 | + } |
| 47 | + |
| 48 | + return ctx.JSON(http.StatusOK, result) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// ReadJSONFromBody read json body |
| 53 | +func ReadJSONFromBody(ctx echo.Context, value interface{}) error { |
| 54 | + data, err := ioutil.ReadAll(ctx.Request().Body) |
| 55 | + if err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + |
| 59 | + if len(data) > 0 { |
| 60 | + err = json.Unmarshal(data, value) |
| 61 | + if err != nil { |
| 62 | + return err |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return nil |
| 67 | +} |
0 commit comments