-
Notifications
You must be signed in to change notification settings - Fork 1
/
servehttp.go
58 lines (55 loc) · 1.65 KB
/
servehttp.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
package jaws
import (
"net/http"
"strconv"
"strings"
)
var headerCacheStatic = []string{"public, max-age=31536000, s-maxage=31536000, immutable"}
var headerCacheNoCache = []string{"no-cache"}
var headerAcceptEncoding = []string{"Accept-Encoding"}
var headerContentType = []string{"application/javascript; charset=utf-8"}
var headerContentGZip = []string{"gzip"}
// ServeHTTP can handle the required JaWS endpoints, which all start with "/jaws/".
func (jw *Jaws) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if len(r.RequestURI) > 6 && strings.HasPrefix(r.RequestURI, "/jaws/") {
if r.RequestURI[6] == '.' {
switch r.RequestURI {
case JavascriptPath:
hdr := w.Header()
hdr["Cache-Control"] = headerCacheStatic
hdr["Content-Type"] = headerContentType
hdr["Vary"] = headerAcceptEncoding
js := JavascriptText
for _, s := range r.Header["Accept-Encoding"] {
for _, v := range strings.Split(s, ",") {
if strings.TrimSpace(v) == "gzip" {
js = JavascriptGZip
hdr["Content-Encoding"] = headerContentGZip
break
}
}
}
hdr["Content-Length"] = []string{strconv.Itoa(len(js))}
_, _ = w.Write(js) // #nosec G104
return
case "/jaws/.ping":
w.Header()["Cache-Control"] = headerCacheNoCache
select {
case <-jw.Done():
w.WriteHeader(http.StatusServiceUnavailable)
default:
w.WriteHeader(http.StatusNoContent)
}
return
}
} else if rq := jw.UseRequest(JawsKeyValue(r.RequestURI[6:]), r); rq != nil {
rq.ServeHTTP(w, r)
return
}
}
w.WriteHeader(http.StatusNotFound)
}