package main import ( "context" "encoding/json" "flag" "fmt" "log" "net/http" "os" "time" ) const VTT_URL string = "http://73.188.175.49:30000" func remoteOnline(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 respondOnline(w http.ResponseWriter, url string, isOnline bool) { data := struct { Online bool `json:"online"` Site string `json:"url"` }{isOnline, url} jsonData, err := json.Marshal(data) if err != nil { http.Error(w, "Error constructing response", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") 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(ctx, VTT_URL) logOnline("Foundry VTT", isOnline) respondOnline(w, VTT_URL, isOnline) } func vttRedirect(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, VTT_URL, http.StatusMovedPermanently) } 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) respondOnline(w, URL, isOnline) } 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)") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0]) fmt.Fprintln(os.Stderr, "Options:") flag.PrintDefaults() } flag.Parse() addr := fmt.Sprintf("%s:%d", *bindAddr, *port) mux := http.NewServeMux() mux.HandleFunc("GET /vtt/status", vttOnline) mux.HandleFunc("GET /vtt", vttRedirect) mux.HandleFunc("GET /site/status", siteOnline) log.Println("Listening on ", addr) log.Fatal(http.ListenAndServe(addr, mux)) }