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
|
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net/http"
"nonsense-time/api"
"nonsense-time/dashboard"
"os"
"time"
)
var logger *slog.Logger
// Middleware to timeout requests after a given duration
func timeoutMiddleware(next http.Handler, duration time.Duration) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), duration)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func main() {
port := flag.Int("p", 8080, "the port to listen on")
bindAddr := flag.String("b", "", "the adress to bind to (leave empty for all interfaces)")
waitTime := flag.Duration("w", 2*time.Second, "the maximum time for a request, unit defaults to ns")
logLevel := flag.String("l", "info", "log level (debug, info, warn, error)")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0])
fmt.Fprintln(os.Stderr, "Options:")
flag.PrintDefaults()
}
flag.Parse()
mux := http.NewServeMux()
loggerOpts := new(slog.HandlerOptions)
switch *logLevel {
case "debug":
loggerOpts.Level = slog.LevelDebug
loggerOpts.AddSource = true
case "info":
loggerOpts.Level = slog.LevelInfo
case "warn":
loggerOpts.Level = slog.LevelDebug
case "error":
loggerOpts.Level = slog.LevelError
default:
panic(fmt.Sprintf("Unkown log level %s", *logLevel))
}
addr := fmt.Sprintf("%s:%d", *bindAddr, *port)
logger = slog.New(slog.NewTextHandler(os.Stdout, loggerOpts))
api.Logger = logger
dashboard.Logger = logger
vtt := timeoutMiddleware(http.HandlerFunc(api.VttOnline), *waitTime)
site := timeoutMiddleware(http.HandlerFunc(api.SiteOnline), *waitTime)
mux.Handle("GET /vtt/status", vtt)
mux.HandleFunc("GET /vtt", api.VttRedirect)
mux.Handle("GET /site/status", site)
mux.HandleFunc("GET /", dashboard.Index)
mux.HandleFunc("GET /static/", dashboard.StaticHandler)
mux.HandleFunc("GET /vtt/logs", api.VttLogs)
logger.Info(fmt.Sprint("Listening on ", addr))
logger.Info(http.ListenAndServe(addr, mux).Error())
}
|