-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
67 lines (53 loc) · 1.39 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
67
package ferry
import (
"net/http"
"github.com/go-chi/chi/v5"
)
// Router is the wrapper of chi.Router which allows to register Procedure and Stream handlers.
// This router is intended to be mounted on regular chi Router.
type Router interface {
// Register registers Procedure or Stream Handler.
Register(...Handler)
chi.Router
}
// NewRouter creates a Router instance. Router is the extension of chi.Router.
func NewRouter(options ...func(m *mux)) Router {
router := chi.NewRouter()
m := &mux{
errHandler: DefaultErrorHandler,
Router: router,
}
notFound := func(w http.ResponseWriter, r *http.Request) {
if err := Encode(w, r, http.StatusNotFound, ClientError{
Code: http.StatusNotFound,
Message: "not found",
}); err != nil {
m.errHandler(w, r, err)
}
}
router.MethodNotAllowed(notFound)
router.NotFound(notFound)
for i := range options {
options[i](m)
}
return m
}
// mux is the implementation of Router interface.
type mux struct {
errHandler ErrorHandler
chi.Router
}
// Register registers Procedure or Stream handlers to the Router.
func (m *mux) Register(handlers ...Handler) {
for _, handler := range handlers {
handler.build(m)
switch h := handler.(type) {
case *procedureHandler:
m.Method(http.MethodPost, "/"+h.meta.name, handler)
case *streamHandler:
m.Method(http.MethodGet, "/"+h.meta.name, handler)
default:
continue
}
}
}