main
1package web
2
3import (
4 "fmt"
5 "net/http"
6 "time"
7
8 "github.com/sirupsen/logrus"
9)
10
11type HttpContext struct {
12 cfg *Configuration
13 log *logrus.Logger
14 mux *http.ServeMux
15}
16
17func NewHttpContext(cfg *Configuration) *HttpContext {
18 logger := logrus.New()
19 logger.SetFormatter(&logrus.TextFormatter{
20 DisableColors: true,
21 DisableLevelTruncation: true,
22 ForceQuote: true,
23 FullTimestamp: true,
24 FieldMap: logrus.FieldMap{
25 logrus.FieldKeyTime: "@timestamp",
26 logrus.FieldKeyLevel: "@level",
27 logrus.FieldKeyMsg: "@message",
28 },
29 })
30
31 return &HttpContext{
32 cfg: cfg,
33 log: logger,
34 }
35}
36
37func (h *HttpContext) Router() *http.ServeMux {
38 mux := http.NewServeMux()
39
40 mux.Handle("/", h.buildHandlerFor(h.Default))
41 mux.Handle("/.well-known/", h.wellKnownMux())
42 mux.Handle("/authorize", h.buildHandlerFor(h.Authorize))
43 mux.Handle("/register", h.buildHandlerFor(h.Register))
44 mux.Handle("/revoke", h.buildHandlerFor(http.NotFound))
45 mux.Handle("/token", h.buildHandlerFor(h.Token))
46 mux.Handle("/userinfo", h.buildHandlerFor(http.NotFound))
47 return mux
48}
49
50func (h *HttpContext) buildHandlerFor(handler http.HandlerFunc) http.Handler {
51 return h.withLogging(http.HandlerFunc(handler))
52}
53
54func (h *HttpContext) wellKnownMux() *http.ServeMux {
55 mux := http.NewServeMux()
56 mux.Handle("/.well-known/jwks.json", h.buildHandlerFor(h.JsonWebKeySets))
57 mux.Handle("/.well-known/openid-configuration", h.buildHandlerFor(h.OpenIdConfiguration))
58 return mux
59}
60
61func (h *HttpContext) withLogging(next http.Handler) http.Handler {
62 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
63 start := time.Now()
64 next.ServeHTTP(w, r)
65 end := time.Now()
66
67 duration := end.Sub(start)
68 h.log.WithFields(logrus.Fields{
69 "method": r.Method,
70 "path": r.URL.Path,
71 "remote_addr": r.RemoteAddr,
72 "user_agent": r.UserAgent(),
73 "µs": duration.Microseconds(),
74 }).Info(fmt.Sprintf("%v %v", r.Method, r.URL.Path))
75 })
76}