forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors_handler.go
50 lines (43 loc) · 1.38 KB
/
cors_handler.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
50
package uadmin
import (
"net/http"
"strings"
)
func CORSHandler(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Add CORS headers
if len(AllowedCORSOrigins) == 0 {
if r.Header.Get("Origin") != "" {
w.Header().Add("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Add("Access-Control-Allow-Credentials", "true")
} else {
w.Header().Add("Access-Control-Allow-Origin", "*")
}
} else {
allowedOrigin := false
for i := range AllowedCORSOrigins {
if strings.EqualFold(r.Header.Get("Origin"), AllowedCORSOrigins[i]) {
allowedOrigin = true
break
}
}
if allowedOrigin {
w.Header().Add("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Add("Access-Control-Allow-Credentials", "true")
} else {
w.Header().Add("Access-Control-Allow-Origin", strings.Join(AllowedCORSOrigins, "|"))
w.Header().Add("Access-Control-Allow-Credentials", "true")
}
}
// Handle preflight requests
if r.Method == http.MethodOptions {
// Allow all known methods
w.Header().Add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, HEAD")
// Allow requested headers
w.Header().Add("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
return
}
// run the handler
f(w, r)
}
}