4df6d17739
All checks were successful
Build and copy to prod / build-and-copy (push) Successful in 34s
76 lines
1.4 KiB
Go
76 lines
1.4 KiB
Go
package ping
|
|
|
|
import (
|
|
"database/sql"
|
|
"net/http"
|
|
|
|
"lewisdale.dev/oopsie/sites"
|
|
)
|
|
|
|
type Status int16
|
|
|
|
const (
|
|
Success Status = iota
|
|
Failure
|
|
)
|
|
|
|
type Ping struct {
|
|
Site sites.Site
|
|
Timestamp string
|
|
Status Status
|
|
}
|
|
|
|
const createQuery = `CREATE TABLE IF NOT EXISTS statuses (
|
|
id INTEGER PRIMARY KEY,
|
|
name TEXT NOT NULL
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS ping (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
site TEXT NOT NULL,
|
|
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
status INTEGER NOT NULL,
|
|
FOREIGN KEY (site) REFERENCES sites(url),
|
|
FOREIGN KEY (status) REFERENCES statuses(id)
|
|
);`
|
|
|
|
const seedStatusQuery = `INSERT INTO statuses (id, name) VALUES (?, ?)
|
|
ON CONFLICT (id) DO NOTHING;`
|
|
|
|
func CreateTable(db *sql.DB) {
|
|
if _, err := db.Exec(createQuery); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
seedStatuses(db)
|
|
}
|
|
|
|
func seedStatuses(db *sql.DB) {
|
|
if _, err := db.Exec(seedStatusQuery, Success, "Success"); err != nil {
|
|
panic(err)
|
|
}
|
|
if _, err := db.Exec(seedStatusQuery, Failure, "Failure"); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
const saveQuery = `INSERT INTO ping (site, status) VALUES (?, ?);`
|
|
|
|
func (p *Ping) Save(db *sql.DB) {
|
|
db.Exec(saveQuery, p.Site.Url, p.Status)
|
|
}
|
|
|
|
func SendPing(db *sql.DB, site sites.Site) {
|
|
p := Ping{
|
|
Site: site,
|
|
}
|
|
|
|
if _, err := http.Get(site.Url); err != nil {
|
|
p.Status = Failure
|
|
} else {
|
|
p.Status = Success
|
|
}
|
|
|
|
p.Save(db)
|
|
}
|