Skip to content

Commit f6b611c

Browse files
dev: 增加一些http辅助方法
1 parent 8c81481 commit f6b611c

File tree

2 files changed

+67
-6
lines changed

2 files changed

+67
-6
lines changed

http.go

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,6 @@ import (
88
md "github.com/labstack/echo/middleware"
99
)
1010

11-
// JsonResult json result
12-
type JsonResult struct {
13-
Code int `json:"code"`
14-
Data interface{} `json:"data"`
15-
}
16-
1711
type httpServer struct {
1812
addr string
1913
server *echo.Echo

http_utils.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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

Comments
 (0)