Skip to content

Commit

Permalink
dev: 增加一些http辅助方法
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangxu19830126 committed Mar 30, 2018
1 parent 8c81481 commit f6b611c
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 6 deletions.
6 changes: 0 additions & 6 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
67 changes: 67 additions & 0 deletions http_utils.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit f6b611c

Please sign in to comment.