blob: abe5f56f4969c1f3213fd8979e3298b66724bcc8 [file] [log] [blame]
Sergiusz Bazanskie653e6a2019-07-20 16:36:00 +02001package schema
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io/ioutil"
8 "net/http"
9 "strings"
10)
11
12func IXURL(id int64) string {
13 return fmt.Sprintf("https://peeringdb.com/api/ix/%d.json?depth=4", id)
14}
15
16func NetIXLanInIXURL(id int64) string {
17 return fmt.Sprintf("https://peeringdb.com/api/netixlan?ix_id__in=%d", id)
18}
19
20func NetURLMulti(ids []int64) string {
21 sid := make([]string, len(ids))
22 for i, id := range ids {
23 sid[i] = fmt.Sprintf("%d", id)
24 }
25 return fmt.Sprintf("https://peeringdb.com/api/net?id__in=%s", strings.Join(sid, ","))
26}
27
28func Get(ctx context.Context, obj interface{}, url string) error {
29 req, err := http.NewRequest("GET", url, nil)
30 if err != nil {
31 return fmt.Errorf("http.NewRequest(GET, %q): %v", url, err)
32 }
33
34 req.Header.Add("User-Agent", "bgpwtf-cccampix-peeringdbproxy/1.0 (https://code.hackerspace.pl/hscloud/bgpwtf/cccampix/peeringdb)")
35
36 req = req.WithContext(ctx)
37
38 client := http.DefaultClient
39 res, err := client.Do(req)
40 if err != nil {
41 return fmt.Errorf("client.Do(%v): %v", req, err)
42 }
43
44 defer res.Body.Close()
45
46 if res.StatusCode != 200 {
47 return fmt.Errorf("got status code %d", res.StatusCode)
48 }
49
50 data, err := ioutil.ReadAll(res.Body)
51 if err != nil {
52 return fmt.Errorf("could not read response: %v", err)
53 }
54
55 err = json.Unmarshal(data, &obj)
56 if err != nil {
57 return fmt.Errorf("could not parse response JSON: %v", err)
58 }
59
60 return nil
61}