-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest-server2.go
81 lines (68 loc) · 1.99 KB
/
rest-server2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"time"
_ "github.com/mattn/go-sqlite3"
)
type temperatureReading struct {
SensorID string `json:"sensor_id"`
Temperature float64 `json:"temperature"`
Timestamp string `json:"timestamp"`
}
type temperatureReading_v2 struct {
SensorID string `json:"sensor_id"`
Temperature float64 `json:"temperature"`
Timestamp string `json:"timestamp"`
Uptime int `json:"sensor_uptime"`
}
func temperatureHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
decoder := json.NewDecoder(r.Body)
// first try to decode with v2 format
var t temperatureReading_v2
err := decoder.Decode(&t)
if err != nil {
// check if it's old format
var t_old temperatureReading
err := decoder.Decode(&t_old)
if err != nil {
http.Error(w, "Error decoding request body", http.StatusBadRequest)
return
}
t.SensorID = t_old.SensorID
t.Temperature = t_old.Temperature
t.Timestamp = t_old.Timestamp
t.Uptime = 0
}
// Open SQLite database
db, err := sql.Open("sqlite3", "./temperatures.db")
if err != nil {
fmt.Printf("Error opening database")
return
}
defer db.Close()
// Parse timestamp
print(t.Timestamp + " " + t.SensorID + " " + "\n")
timestamp, err := time.Parse(time.RFC3339, t.Timestamp)
if err != nil {
fmt.Printf("Error parsing timestamp")
return
}
// Insert temperature reading into database
_, err = db.Exec("INSERT INTO readings (sensor_id, temperature, timestamp, sensor_uptime) VALUES (?, ?, ?, ?)", t.SensorID, t.Temperature, timestamp, t.Uptime)
if err != nil {
fmt.Printf("Error inserting temperature reading into database")
return
}
fmt.Printf("Stored temperature reading from sensor %s: %.2f at %s uptime %d\n", t.SensorID, t.Temperature, t.Timestamp, t.Uptime)
}
func main() {
http.HandleFunc("/temperature", temperatureHandler)
http.ListenAndServe(":7894", nil)
}