-
Notifications
You must be signed in to change notification settings - Fork 55
/
cors.go
43 lines (37 loc) · 1.02 KB
/
cors.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
package serverHandler
import (
"../util"
"net/http"
"strings"
)
func (h *handler) cors(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("Access-Control-Allow-Origin", "*")
header.Set("Access-Control-Allow-Credentials", "true")
if r.Method != http.MethodOptions {
return
}
// Access-Control-Allow-Methods
acAllowMethods := []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodDelete,
http.MethodOptions,
http.MethodTrace,
}
acReqMethods := r.Header["Access-Control-Request-Method"]
if len(acReqMethods) > 0 {
acReqMethod := acReqMethods[0]
if !util.Contains(acAllowMethods, acReqMethod) {
acAllowMethods = append(acAllowMethods, acReqMethod)
}
}
header.Set("Access-Control-Allow-Methods", strings.Join(acAllowMethods, ", "))
// Access-Control-Allow-Headers
acAllowHeaders := r.Header["Access-Control-Request-Headers"]
if len(acAllowHeaders) > 0 {
header.Set("Access-Control-Allow-Headers", strings.Join(acAllowHeaders, ", "))
}
}