Implement library support for Angular-style single page applications

This commit is contained in:
Laurence Withers 2020-02-15 12:26:01 +00:00
commit d5b4fcf0be
2 changed files with 60 additions and 2 deletions

View file

@ -72,6 +72,7 @@ type Handler struct {
dir map[string]*packed.File
headers map[string]string
startTime time.Time
notFound *packed.File
}
// SetHeader allows a custom header to be set on HTTP responses. These are
@ -110,6 +111,28 @@ func (h *Handler) SetIndex(filename string) {
}
}
// SetNotFound allows overriding the returned resource when a request is made
// for a resource that does not exist. The default behaviour would be to return
// a standard HTTP 404 Not Found response; calling this function with an empty
// string will restore that behaviour.
//
// This function will return an error if the named resource is not present in
// the packfile.
func (h *Handler) SetNotFound(notFound string) error {
if notFound == "" {
h.notFound = nil
return nil
}
notFound = path.Clean(notFound)
dir := h.dir[path.Clean(notFound)]
if dir == nil {
return fmt.Errorf("no such resource %q", notFound)
}
h.notFound = dir
return nil
}
// 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.
@ -130,8 +153,11 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
info := h.dir[path.Clean(req.URL.Path)]
if info == nil {
http.NotFound(w, req)
return
if h.notFound == nil {
http.NotFound(w, req)
return
}
info = h.notFound
}
// set standard headers