reader.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package mmdb
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. "github.com/oschwald/maxminddb-golang"
  7. )
  8. type geoip2Country struct {
  9. Country struct {
  10. IsoCode string `maxminddb:"iso_code"`
  11. } `maxminddb:"country"`
  12. }
  13. type IPReader struct {
  14. *maxminddb.Reader
  15. databaseType
  16. }
  17. type ASNReader struct {
  18. *maxminddb.Reader
  19. }
  20. type ASNResult struct {
  21. AutonomousSystemNumber uint32 `maxminddb:"autonomous_system_number"`
  22. AutonomousSystemOrganization string `maxminddb:"autonomous_system_organization"`
  23. }
  24. func (r IPReader) LookupCode(ipAddress net.IP) []string {
  25. switch r.databaseType {
  26. case typeMaxmind:
  27. var country geoip2Country
  28. _ = r.Lookup(ipAddress, &country)
  29. if country.Country.IsoCode == "" {
  30. return []string{}
  31. }
  32. return []string{strings.ToLower(country.Country.IsoCode)}
  33. case typeSing:
  34. var code string
  35. _ = r.Lookup(ipAddress, &code)
  36. if code == "" {
  37. return []string{}
  38. }
  39. return []string{code}
  40. case typeMetaV0:
  41. var record any
  42. _ = r.Lookup(ipAddress, &record)
  43. switch record := record.(type) {
  44. case string:
  45. return []string{record}
  46. case []any: // lookup returned type of slice is []any
  47. result := make([]string, 0, len(record))
  48. for _, item := range record {
  49. result = append(result, item.(string))
  50. }
  51. return result
  52. }
  53. return []string{}
  54. default:
  55. panic(fmt.Sprint("unknown geoip database type:", r.databaseType))
  56. }
  57. }
  58. func (r ASNReader) LookupASN(ip net.IP) ASNResult {
  59. var result ASNResult
  60. r.Lookup(ip, &result)
  61. return result
  62. }