-
Notifications
You must be signed in to change notification settings - Fork 2
/
static.go
67 lines (59 loc) · 1.49 KB
/
static.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package static_dir
import (
"github.com/go-go-golems/parka/pkg/handlers/config"
"github.com/go-go-golems/parka/pkg/server"
fs2 "github.com/go-go-golems/parka/pkg/utils/fs"
"io/fs"
"os"
"strings"
)
type StaticDirHandler struct {
fs fs.FS
localPath string
}
type StaticDirHandlerOption func(handler *StaticDirHandler)
func WithDefaultFS(fs fs.FS, localPath string) StaticDirHandlerOption {
return func(handler *StaticDirHandler) {
if handler.fs == nil {
handler.fs = fs
handler.localPath = localPath
}
}
}
func WithLocalPath(localPath string) StaticDirHandlerOption {
return func(handler *StaticDirHandler) {
if localPath != "" {
if !strings.HasSuffix(localPath, "/") {
localPath = localPath + "/"
}
if localPath[0] == '/' {
handler.fs = os.DirFS(localPath)
} else {
handler.fs = os.DirFS(localPath)
}
}
}
}
func NewStaticDirHandler(options ...StaticDirHandlerOption) *StaticDirHandler {
handler := &StaticDirHandler{}
for _, option := range options {
option(handler)
}
return handler
}
func NewStaticDirHandlerFromConfig(sh *config.Static, options ...StaticDirHandlerOption) *StaticDirHandler {
handler := &StaticDirHandler{}
WithLocalPath(sh.LocalPath)(handler)
for _, option := range options {
option(handler)
}
return handler
}
func (s *StaticDirHandler) Serve(server *server.Server, path string) error {
fs_ := s.fs
if s.localPath != "" {
fs_ = fs2.NewAddPrefixPathFS(s.fs, s.localPath)
}
server.Router.StaticFS(path, fs_)
return nil
}