OSDN Git Service

rename (#465)
[bytom/vapor.git] / toolbar / apinode / node.go
1 package apinode
2
3 import (
4         "encoding/json"
5
6         "github.com/bytom/vapor/errors"
7         "github.com/bytom/vapor/netsync/peers"
8         "github.com/bytom/vapor/toolbar/common"
9 )
10
11 // Node can invoke the api which provide by the full node server
12 type Node struct {
13         hostPort string
14 }
15
16 // NewNode create a api client with target server
17 func NewNode(hostPort string) *Node {
18         return &Node{hostPort: hostPort}
19 }
20
21 type response struct {
22         Status    string          `json:"status"`
23         Data      json.RawMessage `json:"data"`
24         ErrDetail string          `json:"error_detail"`
25 }
26
27 func (n *Node) request(path string, payload []byte, respData interface{}) error {
28         resp := &response{}
29         if err := common.Post(n.hostPort+path, payload, resp); err != nil {
30                 return err
31         }
32
33         if resp.Status != "success" {
34                 return errors.New(resp.ErrDetail)
35         }
36
37         if resp.Data == nil {
38                 return nil
39         }
40
41         return json.Unmarshal(resp.Data, respData)
42 }
43
44 func (n *Node) DisconnectPeer(peerID string) error {
45         url := "/disconnect-peer"
46         payload, err := json.Marshal(struct {
47                 PeerID string `json:"peer_id"`
48         }{
49                 PeerID: peerID,
50         })
51         if err != nil {
52                 return err
53         }
54
55         return n.request(url, payload, nil)
56
57 }
58
59 func (n *Node) ConnectPeer(ip string, port uint16) (*peers.Peer, error) {
60         url := "/connect-peer"
61         payload, err := json.Marshal(struct {
62                 Ip   string `json:"ip"`
63                 Port uint16 `json:"port"`
64         }{
65                 Ip:   ip,
66                 Port: port,
67         })
68         if err != nil {
69                 return nil, errors.Wrap(err, "json marshal")
70         }
71
72         res := &peers.Peer{}
73         return res, n.request(url, payload, res)
74 }