geosite.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package common
  2. import (
  3. "fmt"
  4. "github.com/metacubex/mihomo/component/geodata"
  5. _ "github.com/metacubex/mihomo/component/geodata/memconservative"
  6. "github.com/metacubex/mihomo/component/geodata/router"
  7. _ "github.com/metacubex/mihomo/component/geodata/standard"
  8. C "github.com/metacubex/mihomo/constant"
  9. "github.com/metacubex/mihomo/log"
  10. )
  11. type GEOSITE struct {
  12. *Base
  13. country string
  14. adapter string
  15. matcher router.DomainMatcher
  16. recodeSize int
  17. }
  18. func (gs *GEOSITE) RuleType() C.RuleType {
  19. return C.GEOSITE
  20. }
  21. func (gs *GEOSITE) Match(metadata *C.Metadata) (bool, string) {
  22. domain := metadata.RuleHost()
  23. if len(domain) == 0 {
  24. return false, ""
  25. }
  26. return gs.matcher.ApplyDomain(domain), gs.adapter
  27. }
  28. func (gs *GEOSITE) Adapter() string {
  29. return gs.adapter
  30. }
  31. func (gs *GEOSITE) Payload() string {
  32. return gs.country
  33. }
  34. func (gs *GEOSITE) GetDomainMatcher() router.DomainMatcher {
  35. return gs.matcher
  36. }
  37. func (gs *GEOSITE) GetRecodeSize() int {
  38. return gs.recodeSize
  39. }
  40. func NewGEOSITE(country string, adapter string) (*GEOSITE, error) {
  41. if err := geodata.InitGeoSite(); err != nil {
  42. log.Errorln("can't initial GeoSite: %s", err)
  43. return nil, err
  44. }
  45. matcher, size, err := geodata.LoadGeoSiteMatcher(country)
  46. if err != nil {
  47. return nil, fmt.Errorf("load GeoSite data error, %s", err.Error())
  48. }
  49. log.Infoln("Start initial GeoSite rule %s => %s, records: %d", country, adapter, size)
  50. geoSite := &GEOSITE{
  51. Base: &Base{},
  52. country: country,
  53. adapter: adapter,
  54. matcher: matcher,
  55. recodeSize: size,
  56. }
  57. return geoSite, nil
  58. }
  59. var _ C.Rule = (*GEOSITE)(nil)