From 72122553dd4acc8abf353ebebc9628c3c8e83109 Mon Sep 17 00:00:00 2001 From: Lewis Dale Date: Sun, 12 May 2024 16:54:00 +0100 Subject: [PATCH] Output data as JSON --- main.go | 12 +++++++++++- ping/ping.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index eead14b..b14d124 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "net/http" _ "github.com/mattn/go-sqlite3" @@ -28,7 +29,16 @@ func main() { ping.SendPing(db, failureSite) http.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("This was a GET request!")) + pings := ping.List(db) + + if output, err := json.Marshal(pings); err != nil { + w.Write([]byte(err.Error())) + w.WriteHeader(http.StatusInternalServerError) + return + } else { + w.Header().Set("Content-Type", "application/json") + w.Write(output) + } }) http.HandleFunc("POST /", func(w http.ResponseWriter, r *http.Request) { diff --git a/ping/ping.go b/ping/ping.go index f45a05a..7fbaa07 100644 --- a/ping/ping.go +++ b/ping/ping.go @@ -20,6 +20,12 @@ type Ping struct { Status Status } +type PingResponse struct { + Site sites.Site + Timestamp string + Status string +} + const createQuery = `CREATE TABLE IF NOT EXISTS statuses ( id INTEGER PRIMARY KEY, name TEXT NOT NULL @@ -73,3 +79,25 @@ func SendPing(db *sql.DB, site sites.Site) { p.Save(db) } + +func List(db *sql.DB) []PingResponse { + rows, err := db.Query(`SELECT sites.url as url, sites.name, ping.timestamp as timestamp, statuses.name as status FROM ping + JOIN sites ON ping.site = sites.url + JOIN statuses ON ping.status = statuses.id + ORDER BY timestamp DESC`) + + if err != nil { + panic(err) + } + defer rows.Close() + + pings := make([]PingResponse, 0) + + for rows.Next() { + p := PingResponse{} + rows.Scan(&p.Site.Url, &p.Site.Name, &p.Timestamp, &p.Status) + pings = append(pings, p) + } + + return pings +}