forked from NebulousLabs/Sia
/
gateway.go
51 lines (42 loc) · 1.54 KB
/
gateway.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
package api
import (
"net/http"
"github.com/NebulousLabs/Sia/modules"
"github.com/julienschmidt/httprouter"
)
// GatewayGET contains the fields returned by a GET call to "/gateway".
type GatewayGET struct {
NetAddress modules.NetAddress `json:"netaddress"`
Peers []modules.Peer `json:"peers"`
}
// gatewayHandler handles the API call asking for the gatway status.
func (api *API) gatewayHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
peers := api.gateway.Peers()
// nil slices are marshalled as 'null' in JSON, whereas 0-length slices are
// marshalled as '[]'. The latter is preferred, indicating that the value
// exists but contains no elements.
if peers == nil {
peers = make([]modules.Peer, 0)
}
WriteJSON(w, GatewayGET{api.gateway.Address(), peers})
}
// gatewayConnectHandler handles the API call to add a peer to the gateway.
func (api *API) gatewayConnectHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
addr := modules.NetAddress(ps.ByName("netaddress"))
err := api.gateway.Connect(addr)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}
// gatewayDisconnectHandler handles the API call to remove a peer from the gateway.
func (api *API) gatewayDisconnectHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
addr := modules.NetAddress(ps.ByName("netaddress"))
err := api.gateway.Disconnect(addr)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}