-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
asn.go
44 lines (38 loc) · 997 Bytes
/
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
package ipisp
import (
"fmt"
"strconv"
"strings"
)
// ASN represents an Autonomous Systems Number.
// See https://en.wikipedia.org/wiki/Autonomous_system_(Internet).
type ASN int
// ParseASN parses a string like `AS2341` into ASN `2341`.
func ParseASN(asn string) (ASN, error) {
// A special value from the API.
// More info: https://github.com/ammario/ipisp/issues/10.
if asn == "NA" {
return -1, nil
}
// Make case insensitive
asn = strings.ToUpper(asn)
if len(asn) > 2 && asn[:2] == "AS" {
asn = asn[2:]
}
// Trimming multi asn value to single value
// multi asn causes strconv.Atoi conversion error
// More info: https://github.com/ammario/ipisp/issues/22
asn = strings.Split(asn, " ")[0]
nn, err := strconv.Atoi(asn)
if err != nil {
return -1, fmt.Errorf("parse %q: %w", asn, err)
}
return ASN(nn), nil
}
// String represents an ASN like `5544`` as `AS5544`.`
func (a ASN) String() string {
if a == 0 {
return "N/A"
}
return "AS" + strconv.Itoa(int(a))
}