Skip to content
This repository was archived by the owner on Oct 7, 2024. It is now read-only.

Commit a741629

Browse files
committed
Reversed route building order, added conditional middleware overload.
1 parent 532511a commit a741629

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

gonion.go

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,19 @@ func (composer *Composer) Only() *RouteConstraint {
102102
}
103103
}
104104

105-
//When is a constraint that gives you all the route information to filter upon.
106-
func (rc *RouteConstraint) When(routeFilter func(*RouteModel) bool) *RouteConstraint {
105+
//WhenRouteMatches is a constraint that gives you all the route information to filter upon.
106+
func (rc *RouteConstraint) WhenRouteMatches(routeFilter func(*RouteModel) bool) *RouteConstraint {
107107
rc.routeFilter = routeFilter
108108
return rc
109109
}
110110

111+
//When is a constraint that gives you the option to only apply upon a condition being true
112+
func (rc *RouteConstraint) When(condition func() bool) *RouteConstraint {
113+
return rc.WhenRouteMatches(func(r *RouteModel) bool {
114+
return condition()
115+
})
116+
}
117+
111118
//Get constrains the middleware to only apply for 'GET' requests
112119
func (rc *RouteConstraint) Get() *RouteConstraint {
113120
return rc.methodConstraint("GET")
@@ -134,7 +141,7 @@ func (rc *RouteConstraint) Delete() *RouteConstraint {
134141
}
135142

136143
func (rc *RouteConstraint) methodConstraint(method string) *RouteConstraint {
137-
return rc.When(func(route *RouteModel) bool {
144+
return rc.WhenRouteMatches(func(route *RouteModel) bool {
138145
return route.Method == method
139146
})
140147
}
@@ -162,16 +169,17 @@ type Route struct {
162169
//you have chosen for your application.
163170
func (composer *Composer) BuildRoutes() Routes {
164171
routes := make(Routes, 0, 10)
165-
for _, route := range composer.routeRegistry.routes {
172+
for i := len(composer.routeRegistry.routes) - 1; i >= 0; i-- {
173+
route := composer.routeRegistry.routes[i]
166174
middleware := composer.middlewareRegistry.middlewareFor(route)
167175

168176
handler := build(route.Handler, middleware)
169-
route := &Route{
177+
builtRoute := &Route{
170178
Method: route.Method,
171179
Pattern: route.Pattern,
172180
Handler: handler,
173181
}
174-
routes = append(routes, route)
182+
routes = append(routes, builtRoute)
175183
}
176184
return routes
177185
}

0 commit comments

Comments
 (0)