base_station.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package ipdb
  2. import (
  3. "reflect"
  4. "time"
  5. "os"
  6. )
  7. type BaseStationInfo struct {
  8. CountryName string `json:"country_name"`
  9. RegionName string `json:"region_name"`
  10. CityName string `json:"city_name"`
  11. OwnerDomain string `json:"owner_domain"`
  12. IspDomain string `json:"isp_domain"`
  13. BaseStation string `json:"base_station"`
  14. }
  15. type BaseStation struct {
  16. reader *reader
  17. }
  18. func NewBaseStation(name string) (*BaseStation, error) {
  19. r, e := newReader(name, &BaseStationInfo{})
  20. if e != nil {
  21. return nil, e
  22. }
  23. return &BaseStation{
  24. reader: r,
  25. }, nil
  26. }
  27. func (db *BaseStation) Reload(name string) error {
  28. _, err := os.Stat(name)
  29. if err != nil {
  30. return err
  31. }
  32. reader, err := newReader(name, &BaseStationInfo{})
  33. if err != nil {
  34. return err
  35. }
  36. db.reader = reader
  37. return nil
  38. }
  39. func (db *BaseStation) Find(addr, language string) ([]string, error) {
  40. return db.reader.find1(addr, language)
  41. }
  42. func (db *BaseStation) FindMap(addr, language string) (map[string]string, error) {
  43. data, err := db.reader.find1(addr, language)
  44. if err != nil {
  45. return nil, err
  46. }
  47. info := make(map[string]string, len(db.reader.meta.Fields))
  48. for k, v := range data {
  49. info[db.reader.meta.Fields[k]] = v
  50. }
  51. return info, nil
  52. }
  53. func (db *BaseStation) FindInfo(addr, language string) (*BaseStationInfo, error) {
  54. data, err := db.reader.FindMap(addr, language)
  55. if err != nil {
  56. return nil, err
  57. }
  58. info := &BaseStationInfo{}
  59. for k, v := range data {
  60. sv := reflect.ValueOf(info).Elem()
  61. sfv := sv.FieldByName(db.reader.refType[k])
  62. if !sfv.IsValid() {
  63. continue
  64. }
  65. if !sfv.CanSet() {
  66. continue
  67. }
  68. sft := sfv.Type()
  69. fv := reflect.ValueOf(v)
  70. if sft == fv.Type() {
  71. sfv.Set(fv)
  72. }
  73. }
  74. return info, nil
  75. }
  76. func (db *BaseStation) IsIPv4() bool {
  77. return db.reader.IsIPv4Support()
  78. }
  79. func (db *BaseStation) IsIPv6() bool {
  80. return db.reader.IsIPv6Support()
  81. }
  82. func (db *BaseStation) Languages() []string {
  83. return db.reader.Languages()
  84. }
  85. func (db *BaseStation) Fields() []string {
  86. return db.reader.meta.Fields
  87. }
  88. func (db *BaseStation) BuildTime() time.Time {
  89. return db.reader.Build()
  90. }