-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
69 lines (56 loc) · 1.75 KB
/
handlers.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"fmt"
"log"
"net/http"
)
func logHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s\n", r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func cacheHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Del("If-None-Match")
r.Header.Del("If-Range")
r.Header.Del("If-Modified-Since")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
if r.Proto == "HTTP/1.0" {
w.Header().Set("Pragma", "no-cache")
}
handler.ServeHTTP(w, r)
})
}
func corsHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var origin, method, headers string
origin = r.Header.Get("Origin")
if r.Method == "OPTIONS" {
method = r.Header.Get("Access-Control-Request-Method")
headers = r.Header.Get("Access-Control-Request-Headers")
if len(origin) == 0 || len(method) == 0 {
msg := fmt.Sprintf("%d %s: missing required CORS headers",
http.StatusBadRequest, http.StatusText(http.StatusBadRequest))
http.Error(w, msg, http.StatusBadRequest)
return;
}
}
if len(origin) > 0 {
w.Header().Add("Vary", "Origin")
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if len(method) > 0 {
w.Header().Add("Vary", "Access-Control-Request-Method")
w.Header().Set("Access-Control-Allow-Methods", method)
}
if len(headers) > 0 {
w.Header().Add("Vary", "Access-Control-Request-Headers")
w.Header().Set("Access-Control-Allow-Headers", headers)
}
if r.Method != "OPTIONS" {
handler.ServeHTTP(w, r)
}
})
}