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
|
package api
import "net/http"
const (
corsAllowMethods = "GET, POST, DELETE, OPTIONS"
corsAllowHeaders = "Content-Type, Authorization"
)
func withCORS(allowedOrigins []string, next http.Handler) http.Handler {
if len(allowedOrigins) == 0 {
return next
}
allowed := make(map[string]struct{}, len(allowedOrigins))
for _, origin := range allowedOrigins {
allowed[origin] = struct{}{}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if _, ok := allowed[origin]; ok {
h := w.Header()
h.Set("Access-Control-Allow-Origin", origin)
h.Set("Access-Control-Allow-Methods", corsAllowMethods)
h.Set("Access-Control-Allow-Headers", corsAllowHeaders)
h.Set("Access-Control-Allow-Credentials", "true")
h.Add("Vary", "Origin")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
}
next.ServeHTTP(w, r)
})
}
|