forked from muka/peerjs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
77 lines (66 loc) · 1.24 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
package peer
import (
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
//NewAPI initiate a new API client
func NewAPI(opts Options) API {
return API{
opts: opts,
log: createLogger("api", opts.Debug),
}
}
//API wrap calls to API server
type API struct {
opts Options
log *logrus.Entry
}
func (a *API) buildURL(method string) string {
proto := "http"
if a.opts.Secure {
proto = "https"
}
path := a.opts.Path
if path == "/" {
path = ""
}
return fmt.Sprintf(
"%s://%s:%d%s/%s/%s?ts=%d%d",
proto,
a.opts.Host,
a.opts.Port,
path,
a.opts.Key,
method,
time.Now().UnixNano(),
rand.Int(),
)
}
func (a *API) req(method string) ([]byte, error) {
uri := a.buildURL(method)
resp, err := http.Get(uri)
if err != nil {
return []byte{}, err
}
if resp.StatusCode >= 400 {
return []byte{}, fmt.Errorf("Request %s failed: %s", uri, resp.Status)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
return body, nil
}
//RetrieveID retrieve a ID
func (a *API) RetrieveID() ([]byte, error) {
return a.req("id")
}
//ListAllPeers return the list of available peers
func (a *API) ListAllPeers() ([]byte, error) {
return a.req("peers")
}