home to your local SPACEGIRL 馃挮
arimelody.space
1package view
2
3import (
4 "embed"
5 "errors"
6 "mime"
7 "net/http"
8 "os"
9 "path"
10 "path/filepath"
11)
12
13func ServeEmbedFS(fs embed.FS, dir string) http.Handler {
14 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
15 file, err := fs.ReadFile(filepath.Join(dir, filepath.Clean(r.URL.Path)))
16 if err != nil {
17 http.NotFound(w, r)
18 return
19 }
20
21 w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path)))
22 w.WriteHeader(http.StatusOK)
23
24 w.Write(file)
25 })
26}
27
28func ServeFiles(directory string) http.Handler {
29 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
30 info, err := os.Stat(filepath.Join(directory, filepath.Clean(r.URL.Path)))
31
32 // does the file exist?
33 if err != nil {
34 if errors.Is(err, os.ErrNotExist) {
35 http.NotFound(w, r)
36 return
37 }
38 }
39
40 // is thjs a directory? (forbidden)
41 if info.IsDir() {
42 http.NotFound(w, r)
43 return
44 }
45
46 http.FileServer(http.Dir(directory)).ServeHTTP(w, r)
47 })
48}