/
file_server.go
35 lines (32 loc) · 891 Bytes
/
file_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package httpserver
import (
"fmt"
"net/http"
"strings"
)
// File server handler
func FileServer(dir, prefix string) http.HandlerFunc {
prefix = fmt.Sprintf("/%s/", strings.Trim(prefix, "/"))
fs := http.StripPrefix(prefix, http.FileServer(http.Dir(dir)))
return func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, prefix) {
fs.ServeHTTP(w, r)
return
}
http.NotFound(w, r)
}
}
// File server middleware
func FileServerMiddleware(dir, prefix string) func(http.Handler) http.Handler {
prefix = fmt.Sprintf("/%s/", strings.Trim(prefix, "/"))
fs := http.StripPrefix(prefix, http.FileServer(http.Dir(dir)))
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, prefix) {
fs.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r)
})
}
}