-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.go
91 lines (76 loc) · 2.33 KB
/
server.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package prpl
import (
"bytes"
"strings"
"net/http"
)
func (p *prpl) createHandler() http.Handler {
m := http.NewServeMux()
for path, handler := range p.staticHandlers {
m.Handle(path, handler)
}
for _, build := range p.builds {
m.HandleFunc(build.entrypoint, p.routeHandler)
m.Handle(build.name, http.StripPrefix(build.name, p.staticHandler(http.FileServer(p.root))))
}
m.HandleFunc("/", p.routeHandler)
return m
}
func (p *prpl) routeHandler(w http.ResponseWriter, r *http.Request) {
capabilities := p.browserCapabilities(r.UserAgent())
build := p.builds.findBuild(capabilities)
if build == nil {
http.Error(w, "This browser is not supported", http.StatusInternalServerError)
return
}
h := w.Header()
h.Set("Cache-Control", "public, max-age=0")
if p.usePush {
build.addPushHeaders(w, h, r.URL.Path)
}
build.template.Render(w, r)
}
func (p *prpl) staticHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// TODO: Service worker location should be configurable.
h := w.Header()
if strings.HasSuffix(r.URL.Path, "service-worker.js") {
h.Set("Service-Worker-Allowed", "/")
h.Set("Cache-Control", "private, max-age=0")
} else {
h.Set("Cache-Control", "public, max-age=31536000, immutable")
}
file, found := files[r.URL.Path]
if !found {
next.ServeHTTP(w, r)
return
}
// TODO: if using original prpl-server-node strategy
// add the push headers for *this* push-manifest entry
// build.addPushHeaders(w, h, r.URL.Path)
content := bytes.NewReader(file.data)
http.ServeContent(w, r, r.URL.Path, file.modTime, content)
}
return http.HandlerFunc(fn)
}
func (b *build) addPushHeaders(w http.ResponseWriter, header http.Header, filename string) {
if links, ok := b.pushHeaders[filename]; ok {
// TODO: use actual push if server supports it
// need to add content type to push header info
// if pusher, ok := w.(http.Pusher); ok {
// for _, url := range links {
// pusher.Push(url, &http.PushOptions{
// Header: http.Header{
// "Cache-Control": []string{"public, max-age=31536000, immutable"},
// "Content-Type": []string{"TODO: file content type here"},
// },
// })
// }
// } else {
// otherwise hope there is a proxy that will do it for us
for _, link := range links {
header.Add("Link", link)
}
// }
}
}