Output data as JSON
All checks were successful
Build and copy to prod / build-and-copy (push) Successful in 37s

This commit is contained in:
Lewis Dale 2024-05-12 16:54:00 +01:00
parent 4df6d17739
commit 72122553dd
2 changed files with 39 additions and 1 deletions

12
main.go
View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/json"
"net/http" "net/http"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
@ -28,7 +29,16 @@ func main() {
ping.SendPing(db, failureSite) ping.SendPing(db, failureSite)
http.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { 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) { http.HandleFunc("POST /", func(w http.ResponseWriter, r *http.Request) {

View File

@ -20,6 +20,12 @@ type Ping struct {
Status Status Status Status
} }
type PingResponse struct {
Site sites.Site
Timestamp string
Status string
}
const createQuery = `CREATE TABLE IF NOT EXISTS statuses ( const createQuery = `CREATE TABLE IF NOT EXISTS statuses (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
name TEXT NOT NULL name TEXT NOT NULL
@ -73,3 +79,25 @@ func SendPing(db *sql.DB, site sites.Site) {
p.Save(db) 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
}