diff --git a/.gitignore b/.gitignore index adf8f72..a3938de 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ # Go workspace file go.work +main diff --git a/README.md b/README.md index c3d0081..eaabf20 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,10 @@ # home-server-status -Website to show home server infrastructure up/down indicators \ No newline at end of file +Website to show home server infrastructure up/down indicators + +## Build and run + +```sh +$ go build main.go +$ go run main.go +``` diff --git a/home-server-status.go b/main.go similarity index 74% rename from home-server-status.go rename to main.go index ae6daaf..30aad34 100644 --- a/home-server-status.go +++ b/main.go @@ -1,6 +1,7 @@ -package home_server_status +package main import ( + "encoding/json" "fmt" "log" "net/http" @@ -8,23 +9,15 @@ import ( "time" ) -type Website struct { - WebsiteUrl string - Description string - HasIcon bool - IconUrl string -} - type WebsiteStatus struct { WebsiteUrl string Description string HasIcon bool IconUrl string - IsUp bool } func main() { - websites := []Website{ + websites := []WebsiteStatus{ {WebsiteUrl: "https://media.woubery.com", Description: "Jellyfin Server", HasIcon: true, IconUrl: "jellyfin.webp"}, {WebsiteUrl: "https://printing.woubery.com", Description: "OctoPrint", HasIcon: true, IconUrl: "octoprint.png"}, {WebsiteUrl: "https://code.woubery.com", Description: "Gitea Server", HasIcon: true, IconUrl: "gitea.png"}, @@ -34,23 +27,13 @@ func main() { } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - statuses := make([]WebsiteStatus, 0) - - for _, website := range websites { - isUp := checkWebsite(website.WebsiteUrl) == nil - statuses = append(statuses, WebsiteStatus{ - WebsiteUrl: website.WebsiteUrl, - Description: website.Description, - HasIcon: website.HasIcon, - IconUrl: website.IconUrl, - IsUp: isUp, - }) - } - renderTemplate(w, statuses) + renderTemplate(w, websites) }) + http.HandleFunc("/check", handleCheck) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) fmt.Println("Server listening on http://localhost:8080") + log.Fatal(http.ListenAndServe(":8080", nil)) } @@ -72,6 +55,19 @@ func checkWebsite(website string) error { return nil } +func handleCheck(w http.ResponseWriter, r *http.Request) { + url := r.URL.Query().Get("url") + isUp := checkWebsite(url) == nil + response := struct { + IsUp bool `json:"isUp"` + }{ + IsUp: isUp, + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(response) +} + func renderTemplate(w http.ResponseWriter, statuses []WebsiteStatus) { tmpl := ` @@ -152,6 +148,30 @@ func renderTemplate(w http.ResponseWriter, statuses []WebsiteStatus) { margin-right: 5px; } + + +