From 38fb02f470c32cf2a3f4cb9bef540840d85f9254 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Sun, 23 Jun 2024 19:32:40 +0200 Subject: fix and simplify content-encoding negotiation --- internal/website/filemap.go | 18 +++++++++++++----- internal/website/mux.go | 6 ++---- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/internal/website/filemap.go b/internal/website/filemap.go index 126b67f..1ca242e 100644 --- a/internal/website/filemap.go +++ b/internal/website/filemap.go @@ -16,12 +16,19 @@ import ( ) type File struct { - filename string contentType string etag string alternatives map[string]string } +func (f *File) AvailableEncodings() []string { + encs := []string{} + for enc := range f.alternatives { + encs = append(encs, enc) + } + return encs +} + var files = map[string]*File{} func hashFile(filename string) (string, error) { @@ -49,10 +56,11 @@ func registerFile(urlpath string, fp string) error { return err } f := File{ - filename: fp, - contentType: mime.TypeByExtension(filepath.Ext(fp)), - etag: hash, - alternatives: map[string]string{}, + contentType: mime.TypeByExtension(filepath.Ext(fp)), + etag: hash, + alternatives: map[string]string{ + "identity": fp, + }, } for enc, suffix := range encodings { _, err := os.Stat(fp + suffix) diff --git a/internal/website/mux.go b/internal/website/mux.go index 2d0a830..4cc013e 100644 --- a/internal/website/mux.go +++ b/internal/website/mux.go @@ -80,15 +80,13 @@ func NewMux(cfg *config.Config, root string) (mux *http.ServeMux, err error) { for k, v := range cfg.Extra.Headers { w.Header().Add(k, v) } - enc := nego.NegotiateContentEncoding(r, "br", "gzip") + enc := nego.NegotiateContentEncoding(r, file.AvailableEncodings()...) switch enc { - case "", "identity": - http.ServeFile(w, r, files[urlPath].filename) case "br", "gzip": w.Header().Add("Content-Encoding", enc) w.Header().Add("Content-Type", file.contentType) - http.ServeFile(w, r, files[urlPath].alternatives[enc]) } + http.ServeFile(w, r, files[urlPath].alternatives[enc]) return nil })) -- cgit 1.4.1