-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors-handler.go
48 lines (41 loc) · 1.07 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
package main
import (
"net/http"
"strings"
)
func CorsHandler(p *WebUIPlugin, handler http.Handler, methods ...string) http.HandlerFunc {
var hasOptions bool
for _, method := range methods {
if method == http.MethodOptions {
hasOptions = true
break
}
}
if !hasOptions {
methods = append(methods, http.MethodOptions)
}
return func(res http.ResponseWriter, req *http.Request) {
headers := res.Header()
if p.CORSOrigin != "" {
headers.Set("Access-Control-Allow-Origin", p.CORSOrigin)
}
headers.Set("Access-Control-Allow-Credentials", "true")
if req.Method == http.MethodOptions {
headers.Add("Access-Control-Allow-Methods", strings.Join(methods, ", "))
headers.Add("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization")
return
}
var methodAllowed bool
for _, method := range methods {
if method == req.Method {
methodAllowed = true
break
}
}
if !methodAllowed {
http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
handler.ServeHTTP(res, req)
}
}