dir-server

Simple http(s) server
git clone https://www.brianlane.com/git/dir-server
Log | Files | Refs

commit ad743708e54424cdf3bdfe28f7bb56b63a7209bf
parent 29860982d8ceb91da5d20563979e6b363eca526b
Author: Brian C. Lane <bcl@brianlane.com>
Date:   Sun, 10 May 2020 11:11:27 -0700

Add --single page mode to only serve index.html and existing files

Diffstat:
Mmain.go | 30+++++++++++++++++++++++++++++-
1 file changed, 29 insertions(+), 1 deletion(-)

diff --git a/main.go b/main.go @@ -40,6 +40,7 @@ type cmdlineArgs struct { TLS bool Cert string Key string + SinglePage bool } var cfg = cmdlineArgs{ @@ -48,6 +49,7 @@ var cfg = cmdlineArgs{ TLS: false, Cert: "/var/tmp/cert.pem", Key: "/var/tmp/key.pem", + SinglePage: false, } func init() { @@ -56,6 +58,7 @@ func init() { flag.BoolVar(&cfg.TLS, "tls", cfg.TLS, "Use https instead of http") flag.StringVar(&cfg.Cert, "cert", cfg.Cert, "Path to temporary cert.pem") flag.StringVar(&cfg.Key, "key", cfg.Key, "Path to temporary key.pem") + flag.BoolVar(&cfg.SinglePage, "single", cfg.SinglePage, "Single page app, direct all unknown routes to index.html") flag.Parse() } @@ -137,8 +140,33 @@ func makeSelfSigned(cert, key string) { log.Printf("wrote %s\n", key) } +type singlePageFile struct { + http.File +} + +// singlePageFileServer is an http.FileSystem that returns index.html for all non-existant paths +type singlePageFileServer struct { + http.FileSystem +} + +func (fs singlePageFileServer) Open(name string) (http.File, error) { + file, err := fs.FileSystem.Open(name) + if err != nil { + file, err = fs.FileSystem.Open("/index.html") + if err != nil { + return nil, err + } + } + return singlePageFile{file}, nil +} + func main() { - http.Handle("/", http.FileServer(http.Dir("./"))) + if !cfg.SinglePage { + http.Handle("/", http.FileServer(http.Dir("./"))) + } else { + fs := singlePageFileServer{http.Dir("./")} + http.Handle("/", http.FileServer(fs)) + } listen := fmt.Sprintf("%s:%d", cfg.ListenIP, cfg.ListenPort) if !cfg.TLS {