From dcc1066009f672c80b5546126a2ee08f5d7c9644 Mon Sep 17 00:00:00 2001 From: JP Appel Date: Thu, 12 Sep 2024 17:00:40 -0400 Subject: Add status and redirect endpoints --- nonsense-time.go | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 nonsense-time.go (limited to 'nonsense-time.go') diff --git a/nonsense-time.go b/nonsense-time.go new file mode 100644 index 0000000..ed5faf8 --- /dev/null +++ b/nonsense-time.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "encoding/json" + "log" + "net/http" + "time" +) + +const VTT_URL string = "http://73.188.175.49:30000" + +// If a url is publically reachable during a context +func isOnline(ctx context.Context, url string) bool { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + panic(err) + } + + _, err = http.DefaultClient.Do(req) + if err != nil { + log.Println("Error occured while checking status of", url) + return false + } + + return true +} + +func remoteStatus(w http.ResponseWriter, url string, status bool) { + resp_body := struct { + Online bool `json:"online"` + Site string `json:"url"` + }{status, url} + + jsonData, err := json.Marshal(resp_body) + if err != nil { + http.Error(w, "Error constructing response", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Write(jsonData) +} + +func logStatus(name string, status bool) { + statusText := "offline" + if status { + statusText = "online" + } + + log.Println(name, "is", statusText) +} + +// Check if the vtt is online +func vttStatus(w http.ResponseWriter, req *http.Request) { + ctx, cancel := context.WithTimeout(req.Context(), 3*time.Second) + defer cancel() + + status := isOnline(ctx, VTT_URL) + logStatus("Foundry VTT", status) + remoteStatus(w, VTT_URL, status) + +} + +// Redirect to vtt +func vttRedirect(w http.ResponseWriter, req *http.Request) { + http.Redirect(w, req, VTT_URL, http.StatusMovedPermanently) +} + +// Check if the campaign website is online +func siteStatus(w http.ResponseWriter, req *http.Request) { + ctx, cancel := context.WithTimeout(req.Context(), 3*time.Second) + defer cancel() + + const URL string = "https://dnd.jpappel.xyz" + status := isOnline(ctx, URL) + logStatus("Campaign Website", status) + remoteStatus(w, URL, status) +} + +func main() { + mux := http.NewServeMux() + + mux.HandleFunc("GET /vtt/status", vttStatus) + mux.HandleFunc("GET /vtt", vttRedirect) + mux.HandleFunc("GET /site/status", siteStatus) + + log.Println("Listening on Port 8080") + http.ListenAndServe(":8080", mux) +} -- cgit v1.2.3