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".
This commit is contained in:
Laurence Withers 2019-04-25 14:17:55 +01:00
parent e28f687057
commit be86cbaed3
1 changed files with 23 additions and 0 deletions

View File

@ -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.