Skip to content

Commit

Permalink
feat: use deferred initialization of the asnStore
Browse files Browse the repository at this point in the history
  • Loading branch information
aschmahmann committed Aug 25, 2020
1 parent 1b967eb commit 38b74d1
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions asn.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,10 @@ import (
"github.com/libp2p/go-cidranger"
)

var Store *asnStore
var Store *indirectAsnStore

func init() {
s, err := NewAsnStore()
if err != nil {
panic(err)
}
Store = s
Store = &indirectAsnStore{}
}

type networkWithAsn struct {
Expand Down Expand Up @@ -56,6 +52,17 @@ func (a *asnStore) AsnForIPv6(ip net.IP) (string, error) {
// NewAsnStore returns a `asnStore` that can be queried for the Autonomous System Numbers
// for a given IP address or a multiaddress which contains an IP address.
func NewAsnStore() (*asnStore, error) {
if Store.store == nil {
store, err := newAsnStore()
if err != nil {
return nil, err
}
Store.store = store
}
return Store.store, nil
}

func newAsnStore() (*asnStore, error) {
cr := cidranger.NewPCTrieRanger()

for k, v := range ipv6CidrToAsnMap {
Expand All @@ -71,3 +78,22 @@ func NewAsnStore() (*asnStore, error) {

return &asnStore{cr}, nil
}

type indirectAsnStore struct {
store *asnStore
}

// AsnForIPv6 returns the AS number for the given IPv6 address.
// If no mapping exists for the given IP, this function will
// return an empty ASN and a nil error.
func (a *indirectAsnStore) AsnForIPv6(ip net.IP) (string, error) {
if a.store == nil {
store, err := newAsnStore()
if err != nil {
panic(err)
}
a.store = store
}

return a.store.AsnForIPv6(ip)
}

0 comments on commit 38b74d1

Please sign in to comment.