From 6c75129d3b7b6c240ae67a84efeae222fae0d607 Mon Sep 17 00:00:00 2001 From: JP Appel Date: Fri, 13 Sep 2024 16:31:44 -0400 Subject: Refactor request timeout to middleware --- nonsense-time.go | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) (limited to 'nonsense-time.go') diff --git a/nonsense-time.go b/nonsense-time.go index 6d4d438..14a402a 100644 --- a/nonsense-time.go +++ b/nonsense-time.go @@ -21,7 +21,6 @@ func remoteOnline(ctx context.Context, url string) bool { _, err = http.DefaultClient.Do(req) if err != nil { - log.Println("Error occured while checking status of", url) return false } @@ -44,23 +43,13 @@ func respondOnline(w http.ResponseWriter, url string, isOnline bool) { w.Write(jsonData) } -func logOnline(name string, online bool) { - statusText := "offline" - if online { - statusText = "online" - } - - log.Println(name, "is", statusText) -} - func vttOnline(w http.ResponseWriter, req *http.Request) { - ctx, cancel := context.WithTimeout(req.Context(), 3*time.Second) - defer cancel() + isOnline := remoteOnline(req.Context(), VTT_URL) - isOnline := remoteOnline(ctx, VTT_URL) - logOnline("Foundry VTT", isOnline) + if !isOnline { + log.Println("Foundry VTT is offline") + } respondOnline(w, VTT_URL, isOnline) - } func vttRedirect(w http.ResponseWriter, req *http.Request) { @@ -68,19 +57,28 @@ func vttRedirect(w http.ResponseWriter, req *http.Request) { } func siteOnline(w http.ResponseWriter, req *http.Request) { - ctx, cancel := context.WithTimeout(req.Context(), 3*time.Second) - defer cancel() - const URL string = "https://dnd.jpappel.xyz" - isOnline := remoteOnline(ctx, URL) - logOnline("Campaign Website", isOnline) + isOnline := remoteOnline(req.Context(), URL) + if !isOnline { + log.Println("Campaign Website is offline") + } respondOnline(w, URL, isOnline) } +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") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0]) @@ -94,9 +92,12 @@ func main() { mux := http.NewServeMux() - mux.HandleFunc("GET /vtt/status", vttOnline) + vtt := timeoutMiddleware(http.HandlerFunc(vttOnline), *waitTime) + site := timeoutMiddleware(http.HandlerFunc(siteOnline), *waitTime) + + mux.Handle("GET /vtt/status", vtt) mux.HandleFunc("GET /vtt", vttRedirect) - mux.HandleFunc("GET /site/status", siteOnline) + mux.Handle("GET /site/status", site) log.Println("Listening on ", addr) log.Fatal(http.ListenAndServe(addr, mux)) -- cgit v1.2.3