forked from storezhang/echox
-
Notifications
You must be signed in to change notification settings - Fork 1
/
group_restful.go
84 lines (70 loc) · 1.91 KB
/
group_restful.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package echox
import (
`net/http`
`reflect`
`github.com/labstack/echo/v4`
)
func (g *Group) RestfulPost(path string, handler restfulHandler, opts ...groupOption) *Route {
_options := defaultGroupOptions()
for _, opt := range opts {
opt.applyGroup(_options)
}
return g.restful(
http.MethodPost, path, handler,
http.StatusCreated, http.StatusBadRequest,
_options,
)
}
func (g *Group) RestfulGet(path string, handler restfulHandler, opts ...groupOption) *Route {
_options := defaultGroupOptions()
for _, opt := range opts {
opt.applyGroup(_options)
}
return g.restful(
http.MethodGet, path, handler,
http.StatusOK, http.StatusNoContent,
_options,
)
}
func (g *Group) RestfulPut(path string, handler restfulHandler, opts ...groupOption) *Route {
_options := defaultGroupOptions()
for _, opt := range opts {
opt.applyGroup(_options)
}
return g.restful(
http.MethodPut, path, handler,
http.StatusOK, http.StatusBadRequest,
_options,
)
}
func (g *Group) RestfulDelete(path string, handler restfulHandler, opts ...groupOption) *Route {
_options := defaultGroupOptions()
for _, opt := range opts {
opt.applyGroup(_options)
}
return g.restful(
http.MethodDelete, path, handler,
http.StatusNoContent, http.StatusBadRequest,
_options,
)
}
func (g *Group) restful(method string, path string, handler restfulHandler, successCode int, failedCode int, options *groupOptions) *Route {
return &Route{
Route: g.proxy.Add(method, path, func(ctx echo.Context) (err error) {
var rsp interface{}
if rsp, err = handler(parseContext(ctx)); nil != err {
return
}
if g.checkFailed(rsp) {
err = ctx.NoContent(failedCode)
} else {
options.code = successCode
err = data(ctx, rsp, options.httpOptions)
}
return
}, parseMiddlewares(options.middlewares...)...),
}
}
func (g *Group) checkFailed(rsp interface{}) bool {
return nil == rsp || reflect.ValueOf(rsp).IsZero()
}