github.com/sagernet/sing-box@v1.9.0-rc.20/route/rule_item_geosite.go (about)

     1  package route
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/sagernet/sing-box/adapter"
     7  	"github.com/sagernet/sing-box/log"
     8  	E "github.com/sagernet/sing/common/exceptions"
     9  )
    10  
    11  var _ RuleItem = (*GeositeItem)(nil)
    12  
    13  type GeositeItem struct {
    14  	router   adapter.Router
    15  	logger   log.ContextLogger
    16  	codes    []string
    17  	matchers []adapter.Rule
    18  }
    19  
    20  func NewGeositeItem(router adapter.Router, logger log.ContextLogger, codes []string) *GeositeItem {
    21  	return &GeositeItem{
    22  		router: router,
    23  		logger: logger,
    24  		codes:  codes,
    25  	}
    26  }
    27  
    28  func (r *GeositeItem) Update() error {
    29  	matchers := make([]adapter.Rule, 0, len(r.codes))
    30  	for _, code := range r.codes {
    31  		matcher, err := r.router.LoadGeosite(code)
    32  		if err != nil {
    33  			return E.Cause(err, "read geosite")
    34  		}
    35  		matchers = append(matchers, matcher)
    36  	}
    37  	r.matchers = matchers
    38  	return nil
    39  }
    40  
    41  func (r *GeositeItem) Match(metadata *adapter.InboundContext) bool {
    42  	for _, matcher := range r.matchers {
    43  		if matcher.Match(metadata) {
    44  			return true
    45  		}
    46  	}
    47  	return false
    48  }
    49  
    50  func (r *GeositeItem) String() string {
    51  	description := "geosite="
    52  	cLen := len(r.codes)
    53  	if cLen == 1 {
    54  		description += r.codes[0]
    55  	} else if cLen > 3 {
    56  		description += "[" + strings.Join(r.codes[:3], " ") + "...]"
    57  	} else {
    58  		description += "[" + strings.Join(r.codes, " ") + "]"
    59  	}
    60  	return description
    61  }