Working
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user