aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/nonsense-time.go
blob: e5a680342ea28d74bb0a08ac7eadbcd2e33a8a83 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"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() {

	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", vttStatus)
	mux.HandleFunc("GET /vtt", vttRedirect)
	mux.HandleFunc("GET /site/status", siteStatus)

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