apiary/web/frontend.go

48 lines
1023 B
Go

//go:build !embed
// +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) {
s.serveIndex(frontendDir).ServeHTTP(w, r)
return
}
fs.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func (s *Server) 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()
if _, err := io.Copy(w, f); err != nil {
s.ServerLogger.Warnw("Error writing frontend to client.", "err", err)
}
}
return fn
}