-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
49 lines (36 loc) · 1 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package track
import (
"log"
"net/http"
"strings"
)
type MiddlewareFunc func(http.HandlerFunc) http.HandlerFunc
type middleware interface {
Middleware(handler http.Handler) http.Handler
}
func (mw MiddlewareFunc) Middleware(handler http.HandlerFunc) http.HandlerFunc {
return mw(handler)
}
func (r *Router) Use(mwf ...MiddlewareFunc) {
for _, fn := range mwf {
r.middlewares = append(r.middlewares, fn)
}
}
func CORSMethodMiddleware(r *Router) MiddlewareFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
methods := getMethodsForRoute(r, req).Method
log.Println("debug mux", r.Method)
for _, v := range methods {
if v == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
}
}
next.ServeHTTP(w, req)
})
}
}
func getMethodsForRoute(r *Router, req *http.Request) *Router {
vals := strings.Split(req.URL.Path[1:], "/")
return r.search(vals)
}