refactor mux filemap into files.Reader
1 file changed, 12 insertions(+), 25 deletions(-)
changed files
M internal/website/mux.go → internal/website/mux.go
@@ -7,24 +7,13 @@ "strings" "go.alanpearce.eu/website/internal/config" ihttp "go.alanpearce.eu/website/internal/http" + "go.alanpearce.eu/website/internal/storage/files" + "go.alanpearce.eu/website/templates" "go.alanpearce.eu/x/log" - "go.alanpearce.eu/website/templates" "github.com/benpate/digit" "github.com/kevinpollet/nego" - "gitlab.com/tozd/go/errors" ) - -func CanonicalisePath(path string) (cPath string, differs bool) { - cPath = path - if strings.HasSuffix(path, "/index.html") { - cPath, differs = strings.CutSuffix(path, "index.html") - } else if !strings.HasSuffix(path, "/") && files[path+"/"] != nil { - cPath, differs = path+"/", true - } - - return cPath, differs -} type webHandler func(http.ResponseWriter, *http.Request) *ihttp.Error@@ -62,31 +51,29 @@ } } } -func NewMux(cfg *config.Config, root string, log *log.Logger) (mux *http.ServeMux, err error) { +func NewMux( + cfg *config.Config, + reader *files.Reader, + log *log.Logger, +) (mux *http.ServeMux, err error) { mux = &http.ServeMux{} - - log.Debug("registering content files", "root", root) - err = registerContentFiles(root, log) - if err != nil { - return nil, errors.WithMessagef(err, "registering content files") - } templates.Setup() mux.Handle("/", wrapHandler(cfg, func(w http.ResponseWriter, r *http.Request) *ihttp.Error { - urlPath, shouldRedirect := CanonicalisePath(r.URL.Path) + urlPath, shouldRedirect := reader.CanonicalisePath(r.URL.Path) if shouldRedirect { http.Redirect(w, r, urlPath, 302) return nil } - file := GetFile(urlPath) + file := reader.GetFile(urlPath) if file == nil { return &ihttp.Error{ Message: "File not found", Code: http.StatusNotFound, } } - w.Header().Add("ETag", file.etag) + w.Header().Add("ETag", file.Etag) w.Header().Add("Vary", "Accept-Encoding") w.Header().Add("Content-Security-Policy", cfg.CSP.String()) for k, v := range cfg.Extra.Headers {@@ -96,9 +83,9 @@ enc := nego.NegotiateContentEncoding(r, file.AvailableEncodings()...) switch enc { case "br", "gzip": w.Header().Add("Content-Encoding", enc) - w.Header().Add("Content-Type", file.contentType) + w.Header().Add("Content-Type", file.ContentType) } - http.ServeFile(w, r, files[urlPath].alternatives[enc]) + http.ServeFile(w, r, file.Alternatives[enc]) return nil }, log))