diff options
author | Franck Cuny <franck@lumberjaph.net> | 2013-04-28 15:33:15 -0700 |
---|---|---|
committer | Franck Cuny <franck@lumberjaph.net> | 2013-04-28 15:33:15 -0700 |
commit | d91adacdcf21ae7b9975240cd4c55616ad65d5dd (patch) | |
tree | 404dc89a11a0f38d49e2a1d240ec09bdaef4109f /router.go | |
parent | By calling AddOptions on the router, a route for OPTIONS is added (diff) | |
download | path-router-d91adacdcf21ae7b9975240cd4c55616ad65d5dd.tar.gz |
Generate route to respond with 405 when the HTTP method is not existing.
When the user call `AddNotAllowed` on the router, for each path, a new route will be added for each HTTP method not existing. The new route returns a 405 HTTP error and a header containing the list of allowed HTTP methods.
Diffstat (limited to 'router.go')
-rw-r--r-- | router.go | 31 |
1 files changed, 29 insertions, 2 deletions
diff --git a/router.go b/router.go index 23b8214..65b7763 100644 --- a/router.go +++ b/router.go @@ -10,9 +10,12 @@ import ( type Router struct { routes []*Route knownPaths map[string]map[string]bool + withOptions bool notAllowed bool } +var defaultHTTPMethods = []string{"GET", "HEAD", "PUT", "POST", "PATCH", "OPTIONS"} + func BuildRouter() *Router { router := Router{} router.knownPaths = map[string]map[string]bool{} @@ -20,7 +23,7 @@ func BuildRouter() *Router { } func (self *Router) AddOptions() *Router { - self.notAllowed = true + self.withOptions = true routes := self.GetRouteList() for _, r := range routes { m := self.GetMethodsForPath(r) @@ -35,6 +38,30 @@ func (self *Router) AddOptions() *Router { return self } +func (self *Router) AddNotAllowed() *Router { + self.notAllowed = true + routes := self.GetRouteList() + for _, r := range routes { + methods := self.GetMethodsForPath(r) + supportedMethods := map[string]bool{} + for _, m := range methods { + supportedMethods[m] = true + } + allowed := strings.Join(methods, ", ") + defaultFn := func(req *Request) (Response, error) { + r := Response{Status: 405} + r.AddHeader("Allow", allowed) + return r, nil + } + for _, dm := range defaultHTTPMethods { + if supportedMethods[dm] == false { + self.AddRoute(&Route{Method: dm, Path: r, Code: defaultFn}) + } + } + } + return self +} + func (self *Router) routeIsKnown(route *Route) bool { if self.knownPaths[route.Path] == nil { self.knownPaths[route.Path] = map[string]bool{} @@ -145,7 +172,7 @@ func (self *Router) GetAllRoutes() []*Route { return self.routes } -func (self *Router) GetAllRoutesByMethods (method string) []*Route { +func (self *Router) GetAllRoutesByMethods(method string) []*Route { routes := []*Route{} for _, r := range self.routes { if r.Method == method { |