-
Notifications
You must be signed in to change notification settings - Fork 1
/
corshandler.go
40 lines (33 loc) · 1004 Bytes
/
corshandler.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
package graphql
import (
"net/http"
)
type corsHandler struct {
origins []string
}
func (h *corsHandler) validateOrigin(origin string) bool {
for _, allowedOrigin := range h.origins {
if allowedOrigin == origin || allowedOrigin == "*" {
return true
}
}
return false
}
func (h *corsHandler) addCorsHeaders(rw http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if h.validateOrigin(origin) {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Credentials", "true")
rw.Header().Set("Access-Control-Allow-Methods", "POST")
rw.Header().Set("Access-Control-Allow-Headers", "Content-Type")
}
}
func (h *corsHandler) preflightHandler() http.Handler {
return http.HandlerFunc(h.addCorsHeaders)
}
func (h *corsHandler) gqlMiddleware(gqlHandler http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, r *http.Request) {
h.addCorsHeaders(writer, r)
gqlHandler.ServeHTTP(writer, r)
})
}