70 lines
1.5 KiB
Go
70 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
_ "github.com/go-sql-driver/mysql"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
const DEBUG = true
|
|
|
|
func main() {
|
|
err := setup()
|
|
defer teardown()
|
|
if err == nil {
|
|
startServer()
|
|
}
|
|
}
|
|
|
|
func setup() error {
|
|
err := InitDb()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func teardown() {
|
|
CloseDb()
|
|
}
|
|
|
|
func startServer() {
|
|
port := "8001"
|
|
MainRouter.setGet("/", showCharts)
|
|
MainRouter.setGet("/data/", sendData)
|
|
MainRouter.setPost("/", saveSnapshot)
|
|
fmt.Printf("Listening on port %s...\n", port)
|
|
log.Fatal(http.ListenAndServe(":" + port, nil))
|
|
}
|
|
|
|
func showCharts(w http.ResponseWriter, r *http.Request) error {
|
|
_, err := fmt.Fprint(w, "<h1>Climate Stuff</h1><div>The data will show up here at some stage...</div>")
|
|
return err
|
|
}
|
|
|
|
func sendData(w http.ResponseWriter, r *http.Request) error {
|
|
records, err := getSnapshotRecordsFromDb(50)
|
|
if err != nil {
|
|
return fmt.Errorf("couldn't read rows from the database: %w", err)
|
|
}
|
|
json, err := createJsonFromSnapshotRecords(records)
|
|
if err != nil {
|
|
return fmt.Errorf("couldn't create a json from the records: %w", err)
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, err = fmt.Fprintf(w, string(json))
|
|
return err
|
|
}
|
|
|
|
func saveSnapshot(w http.ResponseWriter, r *http.Request) error {
|
|
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
|
|
if err != nil {
|
|
return fmt.Errorf("couldn't create snapshot from JSON: %w", err)
|
|
}
|
|
err = writeSnapshotToDb(snapshotSub)
|
|
if err != nil {
|
|
return fmt.Errorf("couldn't submit snapshot into the database: %w", err)
|
|
}
|
|
return nil
|
|
} |