This commit is contained in:
Daniel Ledda
2020-11-04 18:08:42 +01:00
parent fccba1e4d7
commit cc8cd4bbc4
3 changed files with 54 additions and 14 deletions

View File

@@ -32,6 +32,7 @@ func teardown() {
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))
@@ -42,17 +43,25 @@ func showCharts(w http.ResponseWriter, r *http.Request) error {
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)
}
_, err = fmt.Fprintf(w, string(json))
return err
}
func saveSnapshot(w http.ResponseWriter, r *http.Request) error {
snapshotSub, err := createSnapshotFromJson(r.Body)
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
if err != nil {
return fmt.Errorf("couldn't create snapshot from JSON: %w", err)
}
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)
_, err = ClimateDb.Query(query)
err = writeSnapshotToDb(snapshotSub)
if err != nil {
return fmt.Errorf("couldn't submit snapshot into the database: %w", err)
}