forked from johannesboyne/gofakes3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcors.go
More file actions
84 lines (75 loc) · 1.6 KB
/
cors.go
File metadata and controls
84 lines (75 loc) · 1.6 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gofakes3
import (
"net/http"
"strings"
)
var (
corsHeaders = []string{
"Accept",
"Accept-Encoding",
"Authorization",
"cache-control",
"Content-Disposition",
"Content-Encoding",
"Content-Length",
"Content-Type",
"X-Amz-Date",
"X-Amz-User-Agent",
"X-CSRF-Token",
"x-amz-acl",
"x-amz-content-sha256",
"x-amz-meta-filename",
"x-amz-meta-from",
"x-amz-meta-private",
"x-amz-meta-to",
"x-amz-security-token",
"x-requested-with",
}
corsHeadersString = strings.Join(corsHeaders, ", ")
)
type withCORS struct {
handler http.Handler
methods string
origin string
headers string
expose string
}
func wrapCORS(handler http.Handler) http.Handler {
return &withCORS{
handler: handler,
methods: "POST, GET, OPTIONS, PUT, DELETE, HEAD",
origin: "*",
headers: corsHeadersString,
expose: "ETag",
}
}
func wrapInsecureCORS(handler http.Handler) http.Handler {
return &withCORS{
handler: handler,
methods: "*",
origin: "*",
headers: "*",
expose: "*",
}
}
func (s *withCORS) ServeHTTP(w http.ResponseWriter, r *http.Request) {
isPreflight := r.Method == "OPTIONS" &&
r.Header.Get("Access-Control-Request-Method") != "" &&
r.Header.Get("Origin") != ""
if isPreflight {
if s.origin != "" {
w.Header().Set("Access-Control-Allow-Origin", s.origin)
}
if s.methods != "" {
w.Header().Set("Access-Control-Allow-Methods", s.methods)
}
if s.headers != "" {
w.Header().Set("Access-Control-Allow-Headers", s.headers)
}
if s.expose != "" {
w.Header().Set("Access-Control-Expose-Headers", s.expose)
}
return
}
s.handler.ServeHTTP(w, r)
}