56 lines
1.2 KiB
Go
56 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"io/ioutil"
|
|
)
|
|
|
|
type SnapshotPayload struct {
|
|
Snapshots []*SnapshotRecord `json:"snapshots"`
|
|
}
|
|
|
|
type SnapshotRecord struct {
|
|
Id int `json:"id"`
|
|
JsonSnapshotSubmission
|
|
}
|
|
|
|
type JsonSnapshotSubmission struct {
|
|
Timestamp string `json:"time"`
|
|
Temp float32 `json:"temp"`
|
|
Humidity float32 `json:"humidity"`
|
|
Co2 float32 `json:"co2"`
|
|
}
|
|
|
|
type SnapshotSubmission struct {
|
|
Timestamp interface{}
|
|
Temp interface{}
|
|
Humidity interface{}
|
|
Co2 interface{}
|
|
}
|
|
|
|
func createSnapshotSubFromJsonBodyStream(jsonBodyStream io.ReadCloser) (*SnapshotSubmission, error) {
|
|
var snapshotSub SnapshotSubmission
|
|
body, err := ioutil.ReadAll(jsonBodyStream)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error reading body stream: %w", err)
|
|
}
|
|
err = jsonBodyStream.Close()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("couldn't close body stream: %w", err)
|
|
}
|
|
err = json.Unmarshal(body, &snapshotSub)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("couldn't unmarshal json: %w", err)
|
|
}
|
|
return &snapshotSub, nil
|
|
}
|
|
|
|
func createJsonFromSnapshotRecords(records []*SnapshotRecord) ([]byte, error) {
|
|
jsonResult, err := json.Marshal(SnapshotPayload{records})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("couldn't marshal json: %w", err)
|
|
}
|
|
return jsonResult, nil
|
|
} |