aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/nonsense-time.go
blob: 6c625a1351642b2c51c801829908a62d6d344d9b (plain) (blame)
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
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
    "nonsense-time/api"
)


var logger *log.Logger

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")
	debug := flag.Bool("v", false, "verbose output")

	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()

	addr := fmt.Sprintf("%s:%d", *bindAddr, *port)
	loggerFlags := 0
	loggerPrefix := ""
	if *debug {
        loggerPrefix = "Nonsense Time: "
		loggerFlags = log.Ldate | log.Ltime | log.Lshortfile
	}
	logger = log.New(os.Stdout, loggerPrefix, loggerFlags)

	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)

	logger.Println("Listening on ", addr)
	logger.Fatal(http.ListenAndServe(addr, mux))
}