diff --git a/router.go b/router.go index b9996d4..9b81a58 100644 --- a/router.go +++ b/router.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. /* -Package router 0.2.10 provides fast HTTP request router. +Package router 0.2.11 provides fast HTTP request router. The router matches incoming requests by the request method and the path. If a handle is registered for this path and method, the router delegates the @@ -168,6 +168,11 @@ func (r *Router) HEAD(path string, h Handle) { r.Handle("HEAD", path, h) } +// OPTIONS is a shortcut for Router Handle("OPTIONS", path, handle) +func (r *Router) OPTIONS(path string, h Handle) { + r.Handle("OPTIONS", path, h) +} + // Handle registers a new request handle with the given path and method. func (r *Router) Handle(method, path string, h Handle) { if r.handlers[method] == nil { @@ -202,6 +207,18 @@ func (r *Router) Lookup(method, path string) (Handle, []Param, bool) { return nil, nil, false } +// AllowedMethods returns list of allowed methods +func (r *Router) AllowedMethods(path string) []string { + var allowed []string + for method, parser := range r.handlers { + if _, _, ok := parser.get(path); ok { + allowed = append(allowed, method) + } + } + + return allowed +} + // Listen and serve on requested host and port. func (r *Router) Listen(hostPort string) { if err := http.ListenAndServe(hostPort, r); err != nil { @@ -239,12 +256,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { return } } - allowed := make([]string, 0, len(r.handlers)) - for method, parser := range r.handlers { - if _, _, ok := parser.get(req.URL.Path); ok { - allowed = append(allowed, method) - } - } + allowed := r.AllowedMethods(req.URL.Path) if len(allowed) == 0 { if r.NotFound != nil {