Use a map to serve files

This commit is contained in:
Ken-Håvard Lieng 2018-11-27 12:07:48 +01:00
parent d24d33d94c
commit df71c54d37
2 changed files with 20 additions and 24 deletions

View File

@ -23,7 +23,6 @@ const longCacheControl = "public, max-age=31536000, immutable"
const disabledCacheControl = "no-cache, no-store, must-revalidate"
type File struct {
Path string
Asset string
GzipAsset []byte
Hash string
@ -45,7 +44,7 @@ func newH2PushAsset(name string) h2PushAsset {
}
var (
files []*File
files = map[string]*File{}
indexStylesheet string
indexScripts []string
@ -120,7 +119,6 @@ func (d *Dispatch) initFileServer() {
}
file := &File{
Path: "/" + assetName,
Asset: asset,
ContentType: contentTypes[filepath.Ext(assetName)],
CacheControl: longCacheControl,
@ -136,7 +134,7 @@ func (d *Dispatch) initFileServer() {
file.GzipAsset = gzipAsset(data)
}
files = append(files, file)
files["/"+assetName] = file
}
serviceWorker = decompressedAsset("sw.js")
@ -219,6 +217,11 @@ func (d *Dispatch) serveFiles(w http.ResponseWriter, r *http.Request) {
return
}
if file, ok := files[r.URL.Path]; ok {
d.serveFile(w, r, file)
return
}
if r.URL.Path == "/sw.js" {
w.Header().Set("Cache-Control", disabledCacheControl)
w.Header().Set("Content-Type", "text/javascript")
@ -234,13 +237,6 @@ func (d *Dispatch) serveFiles(w http.ResponseWriter, r *http.Request) {
return
}
for _, file := range files {
if r.URL.Path == file.Path {
d.serveFile(w, r, file)
return
}
}
d.serveIndex(w, r)
}

View File

@ -166,7 +166,19 @@ func (d *Dispatch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if strings.HasPrefix(r.URL.Path, "/ws") {
if r.URL.Path == "/init" {
referer, err := url.Parse(r.Header.Get("Referer"))
if err != nil {
fail(w, http.StatusInternalServerError)
return
}
state := d.handleAuth(w, r, true, true)
data := getIndexData(r, referer.EscapedPath(), state)
writeJSON(w, r, data)
} else if strings.HasPrefix(r.URL.Path, "/ws") {
if !websocket.IsWebSocketUpgrade(r) {
fail(w, http.StatusBadRequest)
return
@ -180,18 +192,6 @@ func (d *Dispatch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
d.upgradeWS(w, r, state)
} else if strings.HasPrefix(r.URL.Path, "/init") {
referer, err := url.Parse(r.Header.Get("Referer"))
if err != nil {
fail(w, http.StatusInternalServerError)
return
}
state := d.handleAuth(w, r, true, true)
data := getIndexData(r, referer.EscapedPath(), state)
writeJSON(w, r, data)
} else {
d.serveFiles(w, r)
}