-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
110 lines (85 loc) · 2.33 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"embed"
"encoding/json"
"errors"
"flag"
"io/fs"
"log"
"net/http"
"os"
"strings"
"github.com/kradalby/kraweb"
)
const defaultHostname = "hugin"
var (
verbose = flag.Bool("verbose", false, "be verbose")
tailscaleKeyPath = flag.String(
"tailscale-auth-key-path",
"",
"path to tailscale auth key, can be passed as TS_AUTH_KEY",
)
hostname = flag.String("hostname", defaultHostname, "service name")
albumDir = flag.String("album", "", "directory containing a Munin album")
controlURL = flag.String("controlurl", "", "Tailscale Control server, if empty, upstream")
localAddr = flag.String("addr", "localhost:56664", "Local address to listen to")
)
func main() {
if err := Run(); err != nil {
log.Fatalf("failed to start hugin: %s", err)
}
}
func tokenHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokens := make(map[string]string)
env := os.Environ()
for _, kv := range env {
if rest, ok := strings.CutPrefix(kv, "HUGIN_TOKEN_"); ok {
parts := strings.Split(rest, "=")
tokens[strings.ToLower(parts[0])] = parts[1]
}
}
json.NewEncoder(w).Encode(tokens)
})
}
//go:embed dist/*
var distFS embed.FS
func distHandler() http.Handler {
sub, err := fs.Sub(distFS, "dist")
if err != nil {
log.Fatal(err)
}
return http.FileServer(http.FS(sub))
}
func loggingHandler(h http.Handler, dir string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s - %s: %s", r.Method, r.URL.Path, dir+r.URL.Path)
h.ServeHTTP(w, r)
})
}
func Run() error {
flag.Parse()
logger := log.New(os.Stdout, "hugin: ", log.LstdFlags)
k := kraweb.NewKraWeb(
*hostname,
*tailscaleKeyPath,
*controlURL,
*verbose,
*localAddr,
logger,
true,
)
k.Handle("/", distHandler())
k.Handle("/tokens", tokenHandler())
if *albumDir == "" {
log.Printf("--album is required to serve an album")
} else {
log.Printf("Serving content from %s", *albumDir)
k.Handle("/album/", http.StripPrefix("/album", loggingHandler(http.FileServer(http.Dir(*albumDir)), *albumDir)))
k.Handle("/content/", http.StripPrefix("/content", loggingHandler(http.FileServer(http.Dir(*albumDir)), *albumDir)))
}
if *hostname == "" {
return errors.New("--hostname, if specified, cannot be empty")
}
return k.ListenAndServe()
}