-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
66 lines (54 loc) · 1.61 KB
/
router.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 gohttp
import (
"log"
"net/http"
"runtime/debug"
)
type RouterInterface[T HttpContext] interface {
http.Handler
RawHandle(pattern string, handler http.Handler)
Handle(pattern string, handler func(T))
}
type ContextFactory[T HttpContext] interface {
NewContext(w http.ResponseWriter, r *http.Request) T
}
func NewContextFactory(cp CacheProvider) ContextFactory[HttpContext] {
if cp == nil {
cp = newMemoryCache()
}
return &contextFactory{NewSessionManager(cp)}
}
type contextFactory struct {
sessionManager SessionManager
}
func (cf *contextFactory) NewContext(w http.ResponseWriter, r *http.Request) HttpContext {
return NewHttpContext(w, r, cf.sessionManager)
}
func NewRouter[T HttpContext](cf ContextFactory[T]) RouterInterface[T] {
return &router[T]{contextFactory: cf}
}
type router[T HttpContext] struct {
serveMux http.ServeMux
contextFactory ContextFactory[T]
}
func (rt *router[T]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rt.serveMux.ServeHTTP(w, r)
}
func (rt *router[T]) RawHandle(pattern string, handler http.Handler) {
rt.serveMux.Handle(pattern, handler)
}
func (rt *router[T]) Handle(pattern string, handler func(T)) {
rt.serveMux.HandleFunc(pattern, wrapHandler(handler, rt.contextFactory))
}
func wrapHandler[T HttpContext](handler func(T), cf ContextFactory[T]) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
ctx := cf.NewContext(w, r)
defer func() {
if err := recover(); err != nil {
log.Println(err, string(debug.Stack()))
ctx.HttpError(http.StatusInternalServerError)
}
}()
handler(ctx)
}
}