-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_server.go
103 lines (84 loc) · 2.09 KB
/
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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package bin
import (
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
)
func RunFileServer(args []string) {
var (
addr string
mounts StringArgs
err error
fSet *flag.FlagSet
logger *slog.Logger
fileServer http.Handler
)
fSet = flag.NewFlagSet("file_server", flag.ContinueOnError) // flag.ExitOnError
fSet.StringVar(&addr, "addr", "127.0.0.1:1099", "file server listening address")
fSet.Var(&mounts, "mount", "mount local dir to http path, default: ./data/site:/site")
fSet.Usage = func() {
output := flag.CommandLine.Output()
fmt.Fprintf(output, "Usage of file server:\n")
fSet.PrintDefaults()
}
// fmt.Println("~~~ args:", args)
if err = fSet.Parse(args); err != nil {
fmt.Fprintf(os.Stderr, "exit: %v\n", err)
os.Exit(1)
return
}
logger = slog.New(slog.NewJSONHandler(os.Stderr, nil))
defer func() {
if err != nil {
logger.Error("Exit", "error", err)
os.Exit(1)
} else {
logger.Info("Exit")
}
}()
if len(mounts) == 0 {
mounts = []string{"./data/site:/site"}
}
for _, v := range mounts {
dir, site, found := strings.Cut(v, ":")
if dir == "" || !found {
err = fmt.Errorf("Invalid mount %s", v)
return
}
if dir, err = filepath.Abs(dir); err != nil {
err = fmt.Errorf("Can't get absolute path of %s", dir)
return
}
if _, err = os.Stat(dir); os.IsNotExist(err) {
err = fmt.Errorf("Directory does not exist: %s", dir)
return
}
fileServer = http.FileServer(http.Dir(dir))
site = "/" + strings.Trim(site, "/")
// fmt.Println("~~~", site)
http.Handle(site+"/", http.StripPrefix(site, fileServer))
}
logger.Info(
"Starting file server",
"mounts", mounts,
"address", addr,
)
if err = http.ListenAndServe(addr, nil); err != nil {
err = fmt.Errorf("Failed to start server: %w", err)
}
}
// Define a type that will implement the flag.Value interface
type StringArgs []string
// Implement the String method
func (i *StringArgs) String() string {
return strings.Join(*i, ",")
}
// Implement the Set method
func (i *StringArgs) Set(value string) error {
*i = append(*i, value)
return nil
}