/
context.go
66 lines (60 loc) · 1.5 KB
/
context.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
package biu
import (
"net/http"
"github.com/emicklei/go-restful"
"github.com/mpvl/errc"
"github.com/tuotoo/biu/box"
)
// Handle transform a biu handler to a restful.RouteFunction.
func Handle(f func(ctx box.Ctx)) restful.RouteFunction {
return func(request *restful.Request, response *restful.Response) {
c := box.Ctx{
Request: request,
Response: response,
}
if !box.DisableErrHandler {
e := errc.Catch(new(error))
defer e.Handle()
c.ErrCatcher = e
}
f(c)
}
}
// Filter transform a biu handler to a restful.FilterFunction
func Filter(f func(ctx box.Ctx)) restful.FilterFunction {
return func(request *restful.Request, response *restful.Response,
chain *restful.FilterChain) {
c := box.Ctx{
Request: request,
Response: response,
FilterChain: chain,
}
if !box.DisableErrHandler {
e := errc.Catch(new(error))
defer e.Handle()
c.ErrCatcher = e
}
f(c)
}
}
// WrapHandler wraps a biu handler to http.HandlerFunc
func WrapHandler(f func(ctx box.Ctx)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
f(box.Ctx{
Request: restful.NewRequest(r),
Response: restful.NewResponse(w),
})
}
}
// AuthFilter checks if request contains JWT,
// and sets UserID in Attribute if exists,
func AuthFilter(code int) restful.FilterFunction {
return Filter(func(ctx box.Ctx) {
userID, err := ctx.IsLogin()
if ctx.ContainsError(err, code) {
return
}
ctx.SetAttribute("UserID", userID)
ctx.ProcessFilter(ctx.Request, ctx.Response)
})
}