forked from xinsec/kellyframework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
62 lines (49 loc) · 1.56 KB
/
utils.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
package kellyframework
import (
"net/http"
"io"
"github.com/julienschmidt/httprouter"
)
type methodCallLogger struct {
row *AccessLogRow
}
const ServiceHandlerAccessLogRowFillerContextKey = "kellyframework.ServiceHandlerAccessLogRowFiller"
func (l *methodCallLogger) Record(field string, value string) {
l.row.SetRowField(field, value)
}
func ServiceHandlerAccessLogRowFillerFactory(row *AccessLogRow) AccessLogRowFiller {
return &methodCallLogger{row}
}
type Route struct {
Method string
Path string
Function interface{}
BypassRequestBody bool
BypassResponseBody bool
}
func RegisterFunctionsToHTTPRouter(r *httprouter.Router, loggerContextKey interface{}, routes []*Route) error {
for _, rt := range routes {
handler, err := NewServiceHandler(rt.Function, loggerContextKey, rt.BypassRequestBody, rt.BypassResponseBody)
if err != nil {
return err
}
r.Handle(rt.Method, rt.Path, handler.ServeHTTPWithParams)
}
return nil
}
func NewHTTPRouter(routes []*Route) (*httprouter.Router, error) {
router := httprouter.New()
err := RegisterFunctionsToHTTPRouter(router, ServiceHandlerAccessLogRowFillerContextKey, routes)
if err != nil {
return nil, err
}
return router, nil
}
func NewLoggingHTTPRouter(routes []*Route, loggingHeaders []string, logWriter io.Writer) (http.Handler, error) {
router, err := NewHTTPRouter(routes)
if err != nil {
return nil, err
}
return NewAccessLogDecorator(router, logWriter, loggingHeaders, ServiceHandlerAccessLogRowFillerContextKey,
ServiceHandlerAccessLogRowFillerFactory), nil
}