-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
37 lines (32 loc) · 1.21 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
package apieasy
import (
"net/http"
)
type MiddlewareFunc func(http.Handler) http.Handler
func ApiEasyCorsMiddlewareDefault(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") // any source
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Max-Age", "3600") // Allow caching for a period of time (in seconds)
if req.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, req)
})
}
func SetCorsMiddleware(allowedOrigins, allowedMethods, allowedHeaders string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", allowedOrigins)
w.Header().Set("Access-Control-Allow-Methods", allowedMethods)
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}