diff --git a/http.go b/http.go index 335e017..435bf76 100644 --- a/http.go +++ b/http.go @@ -8,12 +8,6 @@ import ( md "github.com/labstack/echo/middleware" ) -// JsonResult json result -type JsonResult struct { - Code int `json:"code"` - Data interface{} `json:"data"` -} - type httpServer struct { addr string server *echo.Echo diff --git a/http_utils.go b/http_utils.go new file mode 100644 index 0000000..5116f69 --- /dev/null +++ b/http_utils.go @@ -0,0 +1,67 @@ +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.NoContent(http.StatusBadRequest) + } + + 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.NoContent(http.StatusBadRequest) + } + + 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 +}