apiary/web/frontend.go
2021-04-10 07:58:01 +02:00

45 lines
887 B
Go

// +build !embed
package web
import (
"io"
"net/http"
"os"
"path/filepath"
)
func (s *Server) FrontendHandler(frontendDir string) http.HandlerFunc {
fs := http.FileServer(http.Dir(frontendDir))
return fs.ServeHTTP
}
func (s *Server) IndexHandler(frontendDir string) http.HandlerFunc {
fs := http.FileServer(http.Dir(frontendDir))
fn := func(w http.ResponseWriter, r *http.Request) {
fname := filepath.Join(frontendDir, r.URL.Path)
_, err := os.Stat(fname)
if os.IsNotExist(err) {
serveIndex(frontendDir).ServeHTTP(w, r)
return
}
fs.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func serveIndex(frontendDir string) http.HandlerFunc {
fn := func(w http.ResponseWriter, r *http.Request) {
fname := filepath.Join(frontendDir, "index.html")
f, err := os.Open(fname)
if err != nil {
panic(err)
}
defer f.Close()
io.Copy(w, f)
}
return fn
}