--fallback=/index.html to account for SPA routing

closes #8
This commit is contained in:
Mykola Gurov 2018-07-10 21:30:09 +02:00
parent c835df9fee
commit e00083992e
2 changed files with 35 additions and 5 deletions

20
fallback.go Normal file
View file

@ -0,0 +1,20 @@
package main
import (
"net/http"
"os"
)
// fallback opens defaultPath when the underlying fs returns os.ErrNotExist
type fallback struct {
defaultPath string
fs http.FileSystem
}
func (fb fallback) Open(path string) (http.File, error) {
f, err := fb.fs.Open(path)
if os.IsNotExist(err) {
return fb.fs.Open(fb.defaultPath)
}
return f, err
}

20
main.go
View file

@ -16,6 +16,7 @@ var (
portPtr = flag.Int("port", 8043, "The listening port") portPtr = flag.Int("port", 8043, "The listening port")
context = flag.String("context", "", "The 'context' path on which files are served, e.g. 'doc' will serve the files at 'http://localhost:<port>/doc/'") context = flag.String("context", "", "The 'context' path on which files are served, e.g. 'doc' will serve the files at 'http://localhost:<port>/doc/'")
path = flag.String("path", "/srv/http", "The path for the static files") path = flag.String("path", "/srv/http", "The path for the static files")
fallbackPath = flag.String("fallback", "", "Default relative to be used when no file requested found. E.g. /index.html")
headerFlag = flag.String("append-header", "", "HTTP response header, specified as `HeaderName:Value` that should be added to all responses.") headerFlag = flag.String("append-header", "", "HTTP response header, specified as `HeaderName:Value` that should be added to all responses.")
basicAuth = flag.Bool("enable-basic-auth", false, "Enable basic auth. By default, password are randomly generated. Use --set-basic-auth to set it.") basicAuth = flag.Bool("enable-basic-auth", false, "Enable basic auth. By default, password are randomly generated. Use --set-basic-auth to set it.")
setBasicAuth = flag.String("set-basic-auth", "", "Define the basic auth. Form must be user:password") setBasicAuth = flag.String("set-basic-auth", "", "Define the basic auth. Form must be user:password")
@ -47,12 +48,21 @@ func main() {
} }
port := ":" + strconv.FormatInt(int64(*portPtr), 10) port := ":" + strconv.FormatInt(int64(*portPtr), 10)
handler := http.FileServer(http.Dir(*path)) var fileSystem http.FileSystem = http.Dir(*path)
pathPrefix := "/"; if *fallbackPath != "" {
fileSystem = fallback{
defaultPath: *fallbackPath,
fs: fileSystem,
}
}
handler := http.FileServer(fileSystem)
pathPrefix := "/"
if len(*context) > 0 { if len(*context) > 0 {
pathPrefix = "/"+*context+"/" pathPrefix = "/" + *context + "/"
handler = http.StripPrefix(pathPrefix, handler) handler = http.StripPrefix(pathPrefix, handler)
} }