2025-06-17 01:15:08 +01:00
|
|
|
package view
|
|
|
|
|
|
|
|
import (
|
2025-09-30 19:03:35 +01:00
|
|
|
"embed"
|
2025-06-17 01:15:08 +01:00
|
|
|
"errors"
|
2025-09-30 19:03:35 +01:00
|
|
|
"mime"
|
2025-06-17 01:15:08 +01:00
|
|
|
"net/http"
|
|
|
|
"os"
|
2025-09-30 19:03:35 +01:00
|
|
|
"path"
|
2025-06-17 01:15:08 +01:00
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
2025-09-30 19:03:35 +01:00
|
|
|
func ServeEmbedFS(fs embed.FS, dir string) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
file, err := fs.ReadFile(filepath.Join(dir, filepath.Clean(r.URL.Path)))
|
|
|
|
if err != nil {
|
|
|
|
http.NotFound(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path)))
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
|
|
|
w.Write(file)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func ServeFiles(directory string) http.Handler {
|
2025-06-17 01:15:08 +01:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
info, err := os.Stat(filepath.Join(directory, filepath.Clean(r.URL.Path)))
|
|
|
|
|
|
|
|
// does the file exist?
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
|
|
http.NotFound(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// is thjs a directory? (forbidden)
|
|
|
|
if info.IsDir() {
|
|
|
|
http.NotFound(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.FileServer(http.Dir(directory)).ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|