embed.go 606 B

12345678910111213141516171819202122232425262728293031323334
  1. package web
  2. import (
  3. "embed"
  4. "io/fs"
  5. "net/http"
  6. "strings"
  7. )
  8. //go:embed all:html
  9. var htmlFS embed.FS
  10. func Handler() http.HandlerFunc {
  11. fsys, err := fs.Sub(htmlFS, "html")
  12. if err != nil {
  13. panic("failed to create sub filesystem: " + err.Error())
  14. }
  15. fileServer := http.FileServer(http.FS(fsys))
  16. return func(w http.ResponseWriter, r *http.Request) {
  17. path := r.URL.Path
  18. if path != "/" {
  19. cleanPath := strings.TrimPrefix(path, "/")
  20. if _, err := fs.Stat(fsys, cleanPath); err == nil {
  21. fileServer.ServeHTTP(w, r)
  22. return
  23. }
  24. }
  25. r.URL.Path = "/"
  26. fileServer.ServeHTTP(w, r)
  27. }
  28. }