From be86cbaed3746ab36238a260291a7c4a5b6ba8e8 Mon Sep 17 00:00:00 2001 From: Laurence Withers Date: Thu, 25 Apr 2019 14:17:55 +0100 Subject: [PATCH] Handler: add SetIndex This allows setting an index.html (or equivalent) filename; this means that we can serve requests to "/foo" with the contents of "/foo/index.html". --- handler.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/handler.go b/handler.go index d8f01e9..13dfb78 100644 --- a/handler.go +++ b/handler.go @@ -5,6 +5,7 @@ import ( "net/http" "os" "path" + "path/filepath" "strconv" "strings" "time" @@ -85,6 +86,28 @@ func (h *Handler) SetHeader(key, value string) { } } +// SetIndex allows setting an index.html (or equivalent) that can be used to +// serve requests landing at a directory. For instance, if a file named +// "/foo/index.html" exists, and this function is called with "index.html", +// then a route will be registered to serve the contents of this file at +// "/foo". Noting that the ServeHTTP handler discards a trailing "/" on non +// root URLs, this means that it will serve equivalent content for requests +// to "/foo/index.html", "/foo/" and "/foo". +// +// Existing routes are not overwritten, and this function could be called +// multiple times with different filenames (noting later calls would not +// overwrite files matching earlier calls). +func (h *Handler) SetIndex(filename string) { + for k, v := range h.dir { + if filepath.Base(k) == filename { + routeToAdd := filepath.Dir(k) + if _, exists := h.dir[routeToAdd]; !exists { + h.dir[routeToAdd] = v + } + } + } +} + // ServeHTTP handles requests for files. It supports GET and HEAD methods, with // anything else returning a 405. Exact path matches are required, else a 404 is // returned.