about summary refs log tree commit diff
path: root/router.go
diff options
context:
space:
mode:
Diffstat (limited to 'router.go')
-rw-r--r--router.go31
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 {