-
Notifications
You must be signed in to change notification settings - Fork 50
/
provider_memory.go
77 lines (64 loc) · 1.96 KB
/
provider_memory.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
package ipread
import (
"net"
"github.com/justtrackio/gosoline/pkg/cfg"
"github.com/justtrackio/gosoline/pkg/log"
"github.com/oschwald/geoip2-golang"
)
type MemoryRecord struct {
CountryIso string `cfg:"country_iso"`
CityName string `cfg:"city_name"`
TimeZone string `cfg:"time_zone"`
}
type memoryProvider struct {
records map[string]*geoip2.City
}
var memoryProviderContainer = make(map[string]*memoryProvider)
func ProvideMemoryProvider(name string) *memoryProvider {
if _, ok := memoryProviderContainer[name]; ok {
return memoryProviderContainer[name]
}
memoryProviderContainer[name] = &memoryProvider{
records: make(map[string]*geoip2.City),
}
return memoryProviderContainer[name]
}
func NewMemoryProvider(_ cfg.Config, _ log.Logger, name string) (Provider, error) {
return ProvideMemoryProvider(name), nil
}
func (p memoryProvider) City(ipAddress net.IP) (*geoip2.City, error) {
ipString := ipAddress.String()
if _, ok := p.records[ipString]; !ok {
return nil, ErrIpNotFound
}
return p.records[ipString], nil
}
func (p memoryProvider) AddRecord(ipString string, record MemoryRecord) {
p.records[ipString] = &geoip2.City{
City: struct {
GeoNameID uint `maxminddb:"geoname_id"`
Names map[string]string `maxminddb:"names"`
}{
Names: map[string]string{
"en": record.CityName,
},
},
Country: struct {
GeoNameID uint `maxminddb:"geoname_id"`
IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
IsoCode string `maxminddb:"iso_code"`
Names map[string]string `maxminddb:"names"`
}{
IsoCode: record.CountryIso,
},
Location: struct {
AccuracyRadius uint16 `maxminddb:"accuracy_radius"`
Latitude float64 `maxminddb:"latitude"`
Longitude float64 `maxminddb:"longitude"`
MetroCode uint `maxminddb:"metro_code"`
TimeZone string `maxminddb:"time_zone"`
}{
TimeZone: record.TimeZone,
},
}
}