-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.go
184 lines (157 loc) · 5.5 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package peeringdb
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
)
const (
baseAPI = "https://www.peeringdb.com/api/"
facilityNamespace = "fac"
carrierNamespace = "carrier"
carrierFacilityNamespace = "carrierfac"
campusNamespace = "campus"
internetExchangeNamespace = "ix"
internetExchangeFacilityNamespace = "ixfac"
internetExchangeLANNamespace = "ixlan"
internetExchangePrefixNamespace = "ixpfx"
networkNamespace = "net"
networkFacilityNamespace = "netfac"
networkInternetExchangeLANNamepsace = "netixlan"
organizationNamespace = "org"
networkContactNamespace = "poc"
)
var (
// ErrBuildingURL is the error that will be returned if the URL to call the
// API cannot be built as expected.
ErrBuildingURL = errors.New("error while building the URL to call the peeringdb api")
// ErrBuildingRequest is the error that will be returned if the HTTP
// request to call the API cannot be built as expected.
ErrBuildingRequest = errors.New("error while building the request to send to the peeringdb api")
// ErrQueryingAPI is the error that will be returned if there is an issue
// while making the request to the API.
ErrQueryingAPI = errors.New("error while querying peeringdb api")
// ErrRateLimitExceeded is the error that will be returned if the API rate
// limit is exceeded.
ErrRateLimitExceeded = errors.New("rate limit exceeded")
)
// API is the structure used to interact with the PeeringDB API. This is the
// main structure of this package. All functions to make API calls are
// associated to this structure.
type API struct {
url string
apiKey string
}
// NewAPI returns a pointer to a new API structure. It uses the publicly known
// PeeringDB API endpoint.
func NewAPI() *API {
return &API{url: baseAPI}
}
// NewAPIWithAuth returns a pointer to a new API structure. The API will point
// to the publicly known PeeringDB API endpoint and will use the provided API
// key for authentication while making API calls.
func NewAPIWithAPIKey(apiKey string) *API {
return &API{
url: baseAPI,
apiKey: apiKey,
}
}
// NewAPIFromURL returns a pointer to a new API structure from a given URL. If
// the given URL is empty it will use the default PeeringDB API URL.
func NewAPIFromURL(url string) *API {
if url == "" {
return NewAPI()
}
return &API{url: url}
}
// NewAPIFromURLWithAPIKey returns a pointer to a new API structure from a given
// URL. If the given URL is empty it will use the default PeeringDB API URL. It
// will use the provided API key for authentication while making API calls.
func NewAPIFromURLWithAPIKey(url, apiKey string) *API {
if url == "" {
return NewAPIWithAPIKey(apiKey)
}
return &API{
url: url,
apiKey: apiKey,
}
}
// formatSearchParameters is used to format parameters for a request. When
// building the search string the keys will be used in the alphabetic order.
func formatSearchParameters(parameters map[string]interface{}) string {
// Nothing in slice, just return empty string
if parameters == nil {
return ""
}
var search string
var keys []string
// Get all map keys
for i := range parameters {
keys = append(keys, i)
}
// Sort the keys slice
sort.Strings(keys)
// For each element, append it to the request separated by a & symbol.
for _, key := range keys {
search = search + "&" + key + "=" + url.QueryEscape(fmt.Sprintf("%v", parameters[key]))
}
return search
}
// formatURL is used to format a URL to make a request on PeeringDB API.
func formatURL(base, namespace string, search map[string]interface{}) string {
return fmt.Sprintf("%s%s?depth=1%s", base, namespace,
formatSearchParameters(search))
}
// lookup is used to query the PeeringDB API given a namespace to use and data
// to format the request. It returns an HTTP response that the caller must
// decode with a JSON decoder.
func (api *API) lookup(namespace string, search map[string]interface{}) (*http.Response, error) {
url := formatURL(api.url, namespace, search)
if url == "" {
return nil, ErrBuildingURL
}
// Prepare the GET request to the API, no need to set a body since
// everything is in the URL
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, ErrBuildingRequest
}
if api.apiKey != "" {
request.Header.Add("Authorization", fmt.Sprintf("Api-Key %s", api.apiKey))
}
// Send the request to the API using a simple HTTP client
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, ErrQueryingAPI
}
// Special handling for PeeringDB rate limit
if response.StatusCode == http.StatusTooManyRequests {
return nil, ErrRateLimitExceeded
}
// Generic handling for non-OK responses
if response.StatusCode != http.StatusOK {
body, _ := io.ReadAll(response.Body)
return nil, fmt.Errorf("%s: %s", response.Status, body)
}
return response, nil
}
// GetASN is a simplified function to get PeeringDB details about a given AS
// number. It basically gets the Net object matching the AS number. If the AS
// number cannot be found, nil is returned.
func (api *API) GetASN(asn int) (*Network, error) {
search := make(map[string]interface{})
search["asn"] = asn
// Actually fetch the Network from PeeringDB
network, err := api.GetNetwork(search)
// Error, so nil pointer returned
if err != nil {
return nil, err
}
if len(*network) == 0 {
return nil, fmt.Errorf("no network found for ASN %d", asn)
}
return &(*network)[0], nil
}