blob: ceb812cee284493bde4d614b933a49d3f5cd425f [file] [log] [blame]
Matteo Scandolo1f49bf52018-11-20 13:56:45 -08001package mux
2
3import (
4 "net/http"
5 "strings"
6)
7
8// MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler.
9// Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed
10// to it, and then calls the handler passed as parameter to the MiddlewareFunc.
11type MiddlewareFunc func(http.Handler) http.Handler
12
13// middleware interface is anything which implements a MiddlewareFunc named Middleware.
14type middleware interface {
15 Middleware(handler http.Handler) http.Handler
16}
17
18// Middleware allows MiddlewareFunc to implement the middleware interface.
19func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler {
20 return mw(handler)
21}
22
23// Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
24func (r *Router) Use(mwf ...MiddlewareFunc) {
25 for _, fn := range mwf {
26 r.middlewares = append(r.middlewares, fn)
27 }
28}
29
30// useInterface appends a middleware to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
31func (r *Router) useInterface(mw middleware) {
32 r.middlewares = append(r.middlewares, mw)
33}
34
35// CORSMethodMiddleware sets the Access-Control-Allow-Methods response header
36// on a request, by matching routes based only on paths. It also handles
37// OPTIONS requests, by settings Access-Control-Allow-Methods, and then
38// returning without calling the next http handler.
39func CORSMethodMiddleware(r *Router) MiddlewareFunc {
40 return func(next http.Handler) http.Handler {
41 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
42 var allMethods []string
43
44 err := r.Walk(func(route *Route, _ *Router, _ []*Route) error {
45 for _, m := range route.matchers {
46 if _, ok := m.(*routeRegexp); ok {
47 if m.Match(req, &RouteMatch{}) {
48 methods, err := route.GetMethods()
49 if err != nil {
50 return err
51 }
52
53 allMethods = append(allMethods, methods...)
54 }
55 break
56 }
57 }
58 return nil
59 })
60
61 if err == nil {
62 w.Header().Set("Access-Control-Allow-Methods", strings.Join(append(allMethods, "OPTIONS"), ","))
63
64 if req.Method == "OPTIONS" {
65 return
66 }
67 }
68
69 next.ServeHTTP(w, req)
70 })
71 }
72}