static.go 593 B

1234567891011121314151617181920212223242526272829303132
  1. package web
  2. import (
  3. "embed"
  4. "io/fs"
  5. "net/http"
  6. "path"
  7. )
  8. //go:embed static/*
  9. var staticFiles embed.FS
  10. func Handler() http.Handler {
  11. sub, err := fs.Sub(staticFiles, "static")
  12. if err != nil {
  13. panic(err)
  14. }
  15. fileServer := http.FileServer(http.FS(sub))
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. clean := path.Clean(r.URL.Path)
  18. if clean == "/" {
  19. http.ServeFileFS(w, r, sub, "index.html")
  20. return
  21. }
  22. if _, err := fs.Stat(sub, clean[1:]); err == nil {
  23. fileServer.ServeHTTP(w, r)
  24. return
  25. }
  26. http.ServeFileFS(w, r, sub, "index.html")
  27. })
  28. }