client.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package client
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/ip2location/ip2location-go/v9"
  6. "github.com/vladimirok5959/golang-ip2location/internal/consts"
  7. )
  8. type Client struct {
  9. ctx context.Context
  10. base *ip2location.DB
  11. }
  12. type Result struct {
  13. City string
  14. CountryLong string
  15. CountryShort string
  16. Region string
  17. }
  18. func New(ctx context.Context, shutdown context.CancelFunc) (*Client, error) {
  19. f, err := consts.DataPathFile("IP2LOCATION-LITE-DB3.BIN")
  20. if err != nil {
  21. return nil, err
  22. }
  23. b, err := ip2location.OpenDB(f)
  24. if err != nil {
  25. return nil, err
  26. }
  27. c := Client{
  28. ctx: ctx,
  29. base: b,
  30. }
  31. return &c, nil
  32. }
  33. func (c *Client) IP2Location(ctx context.Context, ip string) (*Result, error) {
  34. if c.base == nil {
  35. return nil, fmt.Errorf("database is not opened")
  36. }
  37. r, err := c.base.Get_all(ip)
  38. return &Result{
  39. City: r.City,
  40. CountryLong: r.Country_long,
  41. CountryShort: r.Country_short,
  42. Region: r.Region,
  43. }, err
  44. }
  45. func (c *Client) Shutdown(ctx context.Context) error {
  46. c.base.Close()
  47. return nil
  48. }