-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
serve.go
46 lines (37 loc) · 1.09 KB
/
serve.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
36
37
38
39
40
41
42
43
44
45
46
// Package serve provides a static http server anywhere you need one.
package serve
import "net/http"
// Options is a struct for specifying configuration options for a FileServer.
type Options struct {
// Directory is the root directory from which to serve files.
Directory string
// Prefix is a filepath prefix that should be ignored by the FileServer.
Prefix string
}
// FileServer wraps an http.FileServer.
type FileServer struct {
opt Options
handler http.Handler
}
// NewFileServer initializes a FileServer.
func NewFileServer(options ...Options) *FileServer {
var opt Options
if len(options) > 0 {
opt = options[0]
}
fs := &FileServer{
opt: opt,
}
fs.handler = http.StripPrefix(opt.Prefix, http.FileServer(http.Dir(opt.Directory)))
return fs
}
// Use wraps the Handler with middleware(s).
func (fs *FileServer) Use(mws ...func(http.Handler) http.Handler) {
for _, h := range mws {
fs.handler = h(fs.handler)
}
}
// ServeHTTP implements the net/http.Handler interface.
func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fs.handler.ServeHTTP(w, r)
}