-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_readings_handler.go
67 lines (53 loc) · 1.87 KB
/
user_readings_handler.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
package main
import (
"encoding/json"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/lib/pq"
_ "github.com/lib/pq"
)
func UserReadingsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed)
return
}
db := OpenConnection() // Ensure this function exists and properly opens a database connection
defer db.Close()
// Extract user ID from URL path using mux
vars := mux.Vars(r)
userIDStr, ok := vars["user_id"]
if !ok {
http.Error(w, "User ID is required", http.StatusBadRequest)
return
}
userID, err := strconv.Atoi(userIDStr)
if err != nil {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
// Query database for readings belonging to the user
rows, err := db.Query("SELECT id, userid, timestamp, value, torquevalues, asmtimes, motionwastes, setvalue FROM readings WHERE userid = $1", userID)
if err != nil {
http.Error(w, "Database query error", http.StatusInternalServerError)
return
}
defer rows.Close()
var readings []Reading
for rows.Next() {
var reading Reading
err := rows.Scan(&reading.ID, &reading.UserID, &reading.Timestamp, &reading.Value, pq.Array(&reading.TorqueValues), pq.Array(&reading.AsmTimes), pq.Array(&reading.MotionWastes), &reading.SetValue)
if err != nil {
http.Error(w, "Error scanning readings", http.StatusInternalServerError)
return
}
readings = append(readings, reading)
}
readingsBytes, err := json.MarshalIndent(readings, "", "\t")
if err != nil {
http.Error(w, "Error marshaling readings", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(readingsBytes)
}