client.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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(consts.DBFileName)
  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) ReloadDatabase(ctx context.Context) error {
  46. f, err := consts.DataPathFile(consts.DBFileName)
  47. if err != nil {
  48. return err
  49. }
  50. b, err := ip2location.OpenDB(f)
  51. if err != nil {
  52. return err
  53. }
  54. c.base.Close()
  55. c.base = b
  56. return nil
  57. }
  58. func (c *Client) Shutdown(ctx context.Context) error {
  59. c.base.Close()
  60. return nil
  61. }