github.com/kelleygo/clashcore@v1.0.2/rules/common/geosite.go (about)

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