-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (70 loc) · 1.58 KB
/
main.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
package main
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
)
// Usage:
// just-files [<url-path>:<file-path>, ...]
//
// Example:
// $ BIND=127.0.0.1 PORT=8080 just-files /:.
func main() {
if err := run(os.Args); err != nil {
fmt.Println("failure:", err)
os.Exit(1)
}
}
func run(args []string) error {
m, err := paths(args[1:])
if err != nil {
return err
}
lockdown(m)
bind := os.Getenv("BIND")
port := os.Getenv("PORT")
if bind == "" || port == "" {
return errors.New("$BIND and $PORT must be set")
}
log.Println("bind is", bind)
log.Println("port is", port)
s := http.Server{
Addr: fmt.Sprintf("%s:%s", bind, port),
Handler: router(m),
ReadTimeout: 5 * time.Second,
ReadHeaderTimeout: 1 * time.Second,
WriteTimeout: 5 * time.Second,
}
return s.ListenAndServe()
}
func paths(args []string) (map[string]string, error) {
if len(args) == 0 {
return nil, fmt.Errorf("must provide at least one path pair")
}
m := make(map[string]string, len(args))
for _, arg := range args {
tokens := strings.SplitN(arg, ":", 2)
if len(tokens) != 2 {
return nil, fmt.Errorf("arg format must be <url-path>:<file-path>")
}
m[tokens[0]] = tokens[1]
}
return m, nil
}
func router(m map[string]string) http.Handler {
mux := http.NewServeMux()
for urlPath, filePath := range m {
log.Printf("mapping %s -> %s", urlPath, filePath)
mux.Handle(urlPath, http.StripPrefix(urlPath, http.FileServer(http.Dir(filePath))))
}
return mux
}
func check(err error) {
if err != nil {
log.Fatalf("unexpected error: %v", err)
}
}