-
Notifications
You must be signed in to change notification settings - Fork 0
/
requests.go
56 lines (46 loc) · 1.26 KB
/
requests.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
package endpoints
import (
"encoding/json"
"log"
"net/http"
"github.com/eisandbar/BusPool/lion/bus"
"github.com/eisandbar/BusPool/lion/publisher"
. "github.com/eisandbar/BusPool/lion/typing"
"github.com/golang/geo/s2"
)
type RequestServer struct {
BusStore bus.BusStore
Pub publisher.Publisher
}
// Handler for client requests
func (rs RequestServer) RequestPost(w http.ResponseWriter, r *http.Request) {
log.Println("Processing request")
var req Request
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !nonEmptyRequest(req) {
http.Error(w, "Missing fields", http.StatusBadRequest)
return
}
instruction := ReqToInstruction(req)
bus, err := rs.BusStore.FindBus(instruction.Client)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
rs.Pub.Publish(bus, instruction)
}
func nonEmptyRequest(req Request) bool {
return req.Client != nil && len(req.Client) == 2 && req.Dest != nil && len(req.Dest) == 2
}
func ReqToInstruction(req Request) Instruction {
return Instruction{
Client: s2.LatLngFromDegrees(req.Client[0], req.Client[1]),
Dest: s2.LatLngFromDegrees(req.Dest[0], req.Dest[1]),
}
}