-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrouter.go
More file actions
67 lines (56 loc) · 1.75 KB
/
router.go
File metadata and controls
67 lines (56 loc) · 1.75 KB
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
package kitty
import (
"net/http"
)
// Router is an interface for router implementations.
type Router interface {
// Handle registers a handler to the router.
Handle(method string, path string, handler http.Handler)
// SetNotFoundHandler will sets the NotFound handler.
SetNotFoundHandler(handler http.Handler)
// ServeHTTP implements http.Handler.
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
// RouterOption sets optional Router options.
type RouterOption func(Router) Router
// Router defines the router to use in a server.
func (t *HTTPTransport) Router(r Router, opts ...RouterOption) *HTTPTransport {
for _, opt := range opts {
r = opt(r)
}
t.mux = r
return t
}
// StdlibRouter returns a Router based on the stdlib http package.
func StdlibRouter() Router {
return &stdlibRouter{mux: http.NewServeMux()}
}
// NotFoundHandler will set the not found handler of the router.
func NotFoundHandler(h http.Handler) RouterOption {
return func(r Router) Router {
r.SetNotFoundHandler(h)
return r
}
}
var _ Router = &stdlibRouter{}
// StdlibRouter is a Router implementation based on the stdlib http package.
type stdlibRouter struct {
mux *http.ServeMux
}
// Handle registers a handler to the router.
func (g *stdlibRouter) Handle(method, path string, h http.Handler) {
g.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if r.Method == method {
h.ServeHTTP(w, r)
return
}
http.NotFound(w, r)
})
}
// SetNotFoundHandler will do nothing as we cannot override the Not Found handler from the stdlib.
func (g *stdlibRouter) SetNotFoundHandler(h http.Handler) {
}
// ServeHTTP dispatches the handler registered in the matched route.
func (g *stdlibRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
g.mux.ServeHTTP(w, r)
}