...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package main
22
23 import (
24 "net/http"
25 "os"
26 "path/filepath"
27 "strings"
28
29 "github.com/go-chi/chi"
30 "github.com/go-chi/chi/middleware"
31 )
32
33 func main() {
34 r := chi.NewRouter()
35 r.Use(middleware.Logger)
36
37
38 r.Get("/", func(w http.ResponseWriter, r *http.Request) {
39 w.Write([]byte("hi"))
40 })
41
42
43
44 workDir, _ := os.Getwd()
45 filesDir := http.Dir(filepath.Join(workDir, "data"))
46 FileServer(r, "/files", filesDir)
47
48 http.ListenAndServe(":3333", r)
49 }
50
51
52
53 func FileServer(r chi.Router, path string, root http.FileSystem) {
54 if strings.ContainsAny(path, "{}*") {
55 panic("FileServer does not permit any URL parameters.")
56 }
57
58 if path != "/" && path[len(path)-1] != '/' {
59 r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
60 path += "/"
61 }
62 path += "*"
63
64 r.Get(path, func(w http.ResponseWriter, r *http.Request) {
65 rctx := chi.RouteContext(r.Context())
66 pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
67 fs := http.StripPrefix(pathPrefix, http.FileServer(root))
68 fs.ServeHTTP(w, r)
69 })
70 }
71
View as plain text