/
router.go
62 lines (53 loc) · 1.55 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
package router
import (
"fmt"
"net/http"
"strings"
"github.com/BlackBX/service-framework/dependency"
"github.com/BlackBX/service-framework/response"
"github.com/gorilla/mux"
"go.uber.org/fx"
)
// Service is how the dependency is provided to the dependency builder
var Service = dependency.Service{
Dependencies: fx.Provide(
func(router *mux.Router) http.Handler {
return router
},
),
Constructor: New,
}
// ApplierFunc is a function type that allows routes to be applied to
// the main router
type ApplierFunc func(router *mux.Router)
// Module is a group of routes to route to based on a path
type Module struct {
Path string
Router ApplierFunc
}
// PathPrefix returns the path with a slash at the start
func (m Module) PathPrefix() string {
if strings.HasPrefix(m.Path, "/") {
return m.Path
}
return fmt.Sprintf("/%s", m.Path)
}
// Params are the parameters required to build the router
type Params struct {
fx.In
ResponseProvider response.ResponderProvider
Modules []Module `group:"server"`
Middlewares []mux.MiddlewareFunc `group:"middleware"`
}
// New creates a new instance of a *mux.Router with all of the modules added
func New(params Params) *mux.Router {
router := mux.NewRouter()
for _, module := range params.Modules {
subRouter := router.PathPrefix(module.PathPrefix()).Subrouter()
module.Router(subRouter)
}
router.Use(params.Middlewares...)
router.NotFoundHandler = New404Handler(params.ResponseProvider)
router.MethodNotAllowedHandler = New405Handler(params.ResponseProvider)
return router
}