Got it working!
This commit is contained in:
60
climate-server.go
Normal file
60
climate-server.go
Normal file
@@ -0,0 +1,60 @@
|
||||
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.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 saveSnapshot(w http.ResponseWriter, r *http.Request) error {
|
||||
snapshotSub, err := createSnapshotFromJson(r.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("couldn't create snapshot from JSON: %w", err)
|
||||
}
|
||||
_, err = ClimateDb.Query(
|
||||
fmt.Sprintf("INSERT INTO `snapshots` (`temp`, `humidity`, `co2`, `time`, `id`) VALUES (%v, %v, %v, %v, NULL);",
|
||||
snapshotSub.Temp,
|
||||
snapshotSub.Humidity,
|
||||
snapshotSub.Co2,
|
||||
snapshotSub.Timestamp))
|
||||
if err != nil {
|
||||
return fmt.Errorf("couldn't submit snapshot into the database: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user