/
context.go
73 lines (64 loc) · 1.8 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
67
68
69
70
71
72
73
package biu
import (
"log/slog"
"net/http"
"github.com/emicklei/go-restful/v3"
"github.com/mpvl/errc"
"github.com/tuotoo/biu/auth"
"github.com/tuotoo/biu/box"
)
// Handle transform a biu handler to a restful.RouteFunction.
func Handle(f func(ctx box.Ctx)) restful.RouteFunction {
return HandleWithLogger(f, DefaultContainer.logger)
}
func HandleWithLogger(f func(ctx box.Ctx), logger *slog.Logger) restful.RouteFunction {
return func(request *restful.Request, response *restful.Response) {
c := box.Ctx{
Request: request,
Response: response,
Logger: logger,
}
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 FilterWithLogger(f, DefaultContainer.logger)
}
func FilterWithLogger(f func(ctx box.Ctx), logger *slog.Logger) restful.FilterFunction {
return func(request *restful.Request, response *restful.Response,
chain *restful.FilterChain) {
c := box.Ctx{
Request: request,
Response: response,
FilterChain: chain,
Logger: logger,
}
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, i *auth.Instance) restful.FilterFunction {
return FilterWithLogger(func(ctx box.Ctx) {
userID, err := ctx.IsLogin(i)
ctx.Must(err, code)
ctx.SetAttribute(box.BiuAttrAuthUserID, userID)
ctx.Next()
}, DefaultContainer.logger)
}