-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8c81481
commit f6b611c
Showing
2 changed files
with
67 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |