-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathasn.go
53 lines (43 loc) · 1.14 KB
/
asn.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
package cdn_ranges
import (
"context"
"encoding/json"
"fmt"
"sync"
"go.uber.org/ratelimit"
)
var (
rateLimiterOnce sync.Once
rateLimiter ratelimit.Limiter
)
type IPGuideResponse struct {
Asn int `json:"asn"`
Name string `json:"name"`
Organization string `json:"organization"`
Country string `json:"country"`
Rir string `json:"rir"`
Routes struct {
V4 []string `json:"v4"`
V6 []string `json:"v6"`
} `json:"routes"`
}
// GetRateLimit returns a global reusable rate limiter
func GetRateLimit() ratelimit.Limiter {
rateLimiterOnce.Do(func() {
rateLimiter = ratelimit.New(3)
})
return rateLimiter
}
// ASNPrefixes fetches IPv4 and IPv6 prefixes for a given ASN
func ASNPrefixes(ctx context.Context, asn int) ([]string, []string, error) {
GetRateLimit().Take()
resp, err := HttpGet(ctx, fmt.Sprintf("https://ip.guide/AS%d", asn))
if err != nil {
return nil, nil, err
}
var response IPGuideResponse
if err := json.Unmarshal(resp, &response); err != nil {
return nil, nil, fmt.Errorf("failed to perform unmarshal json: %w", err)
}
return response.Routes.V4, response.Routes.V6, nil
}