forked from brocaar/chirpstack-network-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_gateway_handler.go
88 lines (78 loc) · 1.74 KB
/
api_gateway_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package loraserver
import (
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"github.com/brocaar/loracontrol"
"github.com/brocaar/lorawan"
"github.com/gorilla/mux"
)
// GatewayObjectHandler is a http.Handler which handles requests
// on a single object.
type GatewayObjectHandler struct {
Client *loracontrol.Client
}
func (h *GatewayObjectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
APIError{
Code: http.StatusInternalServerError,
Message: "no id parameter",
}.write(w)
return
}
var mac lorawan.EUI64
b, err := hex.DecodeString(id)
if err != nil {
APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
}.write(w)
return
}
if len(b) != len(mac) {
APIError{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("a gateway MAC is exactly %d bytes", len(mac)),
}.write(w)
return
}
copy(mac[:], b)
switch r.Method {
case "GET":
h.serveGET(w, r, mac)
default:
APIError{
Code: http.StatusMethodNotAllowed,
Message: "method not allowed",
}.write(w)
}
}
func (h *GatewayObjectHandler) serveGET(w http.ResponseWriter, r *http.Request, mac lorawan.EUI64) {
gw, err := h.Client.Gateway().Get(mac)
if err != nil {
if err == loracontrol.ErrObjectDoesNotExist {
APIError{
Code: http.StatusNotFound,
Message: err.Error(),
}.write(w)
return
}
APIError{
Code: http.StatusInternalServerError,
Message: err.Error(),
}.write(w)
return
}
enc := json.NewEncoder(w)
if err := enc.Encode(gw); err != nil {
APIError{
Code: http.StatusInternalServerError,
Message: err.Error(),
}.write(w)
}
}