aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/api/api.go
blob: 3e0dc278b6d0811b233bca4d2f3fac410e6dd541 (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
package api

import (
	"context"
	"encoding/json"
	"log/slog"
	"net/http"
	"os"
)

var Logger *slog.Logger

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 {
		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)
		Logger.Error("Error marshalling site status data")
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(jsonData)
}

func VttOnline(w http.ResponseWriter, req *http.Request) {
	isOnline := remoteOnline(req.Context(), VTT_URL)

	if !isOnline {
		Logger.DebugContext(req.Context(), "Foundry VTT is offline")
	}
	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) {
	const URL string = "https://dnd.jpappel.xyz"

	isOnline := remoteOnline(req.Context(), URL)
	if !isOnline {
		Logger.DebugContext(req.Context(), "Campaign Website is offline")
	}

	respondOnline(w, URL, isOnline)
}

func init() {
	Logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
}