-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutingDefinition.go
73 lines (66 loc) · 2.53 KB
/
routingDefinition.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
68
69
70
71
72
73
package httplayer
import (
"net/http"
)
// RoutingDefinition represents a slice of Route
type RoutingDefinition struct {
commonMiddleware []Middleware
routes []Route
}
// NewDefinition returns a new *RoutingDefinition instance.
// The provided middleware functions are injected into the routes added after this call.
// The middleware functions are executed sequentially in the order they are provided.
//
// Usage:
// - start with NewDefinition() and pass some middleware e.g. firstMiddleware, secondMiddleware, etc.
// - add routes using Add method.
// - invoke Build to return a slice of Route.
//
// Example:
// NewDefinition(firstMiddleware, secondMiddleware).
// Add(http.MethodGet, "/path", handler1).
// Add(http.MethodPost, "/path2", handler2, anotherMiddleware)
//
// Resulting stack for routes:
// - (GET /path): firstMiddleware => secondMiddleware => handler1
// - (POST /path2): firstMiddleware => secondMiddleware => anotherMiddleware => handler2
func NewDefinition(m ...Middleware) *RoutingDefinition {
commonMiddleware := make([]Middleware, 0)
commonMiddleware = append(commonMiddleware, m...)
return &RoutingDefinition{routes: make([]Route, 0), commonMiddleware: commonMiddleware}
}
// Add saves a Route into *RoutingDefinition instance
//
// Example:
//
// def := NewDefinition()
// def.Route("GET", "/api/v1/users", func..., m1, m2, m3)
func (m *RoutingDefinition) Add(method string, path string, h http.HandlerFunc, mid ...Middleware) *RoutingDefinition {
return m.AddMany([]string{method}, path, h, mid...)
}
// AddMany is like Add but this function can address more than one http method with the same handler.
func (m *RoutingDefinition) AddMany(methods []string, path string, h http.HandlerFunc, mid ...Middleware) *RoutingDefinition {
builder := NewBuilder(methods...).Path(path).Handler(h)
allMws := m.commonMiddleware
if len(mid) > 0 {
allMws = append(allMws, mid...)
}
builder.Middleware(allMws...)
m.routes = append(m.routes, builder.Build())
return m
}
// Detach creates a new RoutingDefinition by concatenating the current middlewares from m into
// the newly created RoutingDefinition
func (m *RoutingDefinition) Detach(mid ...Middleware) *RoutingDefinition {
allMiddleware := make([]Middleware, 0)
allMiddleware = append(allMiddleware, m.commonMiddleware...)
allMiddleware = append(allMiddleware, mid...)
return &RoutingDefinition{
commonMiddleware: allMiddleware,
routes: make([]Route, 0),
}
}
// Done returns the slice of Route.
func (m *RoutingDefinition) Done() []Route {
return m.routes
}