-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
28 lines (24 loc) · 792 Bytes
/
middleware.go
File metadata and controls
28 lines (24 loc) · 792 Bytes
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
package httpbulb
import "net/http"
// Cors middleware to handle Cross Origin Resource Sharing (CORS).
func Cors(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
origin = "*"
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
w.Header().Set("Access-Control-Max-Age", "3600")
if acrh, ok := r.Header["Access-Control-Request-Headers"]; ok {
for _, v := range acrh {
w.Header().Add("Access-Control-Allow-Headers", v)
}
}
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}