-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.go
103 lines (90 loc) · 2.44 KB
/
api.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"database/sql"
"encoding/json"
"net/http"
"time"
"github.com/PiotrTopa/js8web/model"
)
func parseTimestamp(t string) (time.Time, error) {
return time.Parse(time.RFC3339, t)
}
func apiStationInfoGet(w http.ResponseWriter, req *http.Request, db *sql.DB) {
stationInfoJson, err := json.Marshal(stationInfoCache)
if err != nil {
logger.Sugar().Errorw(
"Cannot marshal stationInfo",
"stationInfo", stationInfoCache,
"error", err,
)
http.Error(w, "cannot marshal json", http.StatusInternalServerError)
return
}
w.Write(stationInfoJson)
}
func apiRigStatusGet(w http.ResponseWriter, req *http.Request, db *sql.DB) {
rigStatusJson, err := json.Marshal(rigStatusCache)
if err != nil {
logger.Sugar().Errorw(
"Cannot marshal rigStatus",
"rigStatus", rigStatusCache,
"error", err,
)
http.Error(w, "cannot marshal json", http.StatusInternalServerError)
return
}
w.Write(rigStatusJson)
}
func apiRxPacketsGet(w http.ResponseWriter, req *http.Request, db *sql.DB) {
q := req.URL.Query()
if !q.Has("startTime") {
http.Error(w, "'startTime' parameter is required", http.StatusBadRequest)
return
}
startTime, err := parseTimestamp(q.Get("startTime"))
if err != nil {
logger.Sugar().Warnw(
"Cannot parse timestamp",
"time", startTime,
"error", err,
)
http.Error(w, "cannot parse timestamp in 'startTime' parameter", http.StatusBadRequest)
return
}
if !q.Has("direction") {
http.Error(w, "'direction' parameter is required", http.StatusBadRequest)
return
}
direction := q.Get("direction")
if direction != "after" && direction != "before" {
http.Error(w, "'direction' parameter has to be 'before' or 'after'", http.StatusBadRequest)
return
}
filter := &model.RxPacketFilter{}
if q.Has("filter") {
err := json.Unmarshal([]byte(q.Get("filter")), filter)
if err != nil {
http.Error(w, "unable to parse filter", http.StatusInternalServerError)
return
}
}
list, err := model.FetchRxPacketList(db, filter, startTime, direction)
if err != nil {
logger.Sugar().Errorw(
"Cannot fetch RxPacket records from DB",
"error", err,
)
http.Error(w, "cannot fetch RxPacket records", http.StatusInternalServerError)
return
}
response, err := json.Marshal(list)
if err != nil {
logger.Sugar().Errorw(
"Cannot marshal RxPacket records json",
"error", err,
)
http.Error(w, "cannot marshal RxPacket records", http.StatusInternalServerError)
return
}
w.Write(response)
}