-
Notifications
You must be signed in to change notification settings - Fork 10
/
country_lookup.go
70 lines (61 loc) · 1.15 KB
/
country_lookup.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
package statsig
import (
"sync"
"github.com/statsig-io/ip3country-go/pkg/countrylookup"
)
type countryLookup struct {
lookup *countrylookup.CountryLookup
wg sync.WaitGroup
options IPCountryOptions
mu sync.RWMutex
}
func newCountryLookup(options IPCountryOptions) *countryLookup {
countryLookup := &countryLookup{
lookup: nil,
wg: sync.WaitGroup{},
options: options,
}
countryLookup.delayedSetup()
return countryLookup
}
func (c *countryLookup) isReady() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.lookup != nil
}
func (c *countryLookup) delayedSetup() {
if c.options.Disabled {
return
}
c.wg.Add(1)
go func() {
defer c.wg.Done()
c.mu.Lock()
c.lookup = countrylookup.New()
c.mu.Unlock()
}()
}
func (c *countryLookup) init() {
if !c.options.LazyLoad {
c.ensureLoaded()
}
}
func (c *countryLookup) ensureLoaded() {
if c.options.Disabled {
return
}
c.wg.Wait()
}
func (c *countryLookup) lookupIp(ip string) (string, bool) {
if c.options.Disabled {
return "", false
}
if c.options.EnsureLoaded {
c.wg.Wait()
}
if c.isReady() {
val, ok := c.lookup.LookupIp(ip)
return val, ok
}
return "", false
}