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

     1  package main
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  
     7  	"github.com/sagernet/sing-box/common/geosite"
     8  )
     9  
    10  type searchGeositeMatcher struct {
    11  	domainMap   map[string]bool
    12  	suffixList  []string
    13  	keywordList []string
    14  	regexList   []string
    15  }
    16  
    17  func newSearchGeositeMatcher(items []geosite.Item) (*searchGeositeMatcher, error) {
    18  	options := geosite.Compile(items)
    19  	domainMap := make(map[string]bool)
    20  	for _, domain := range options.Domain {
    21  		domainMap[domain] = true
    22  	}
    23  	rule := &searchGeositeMatcher{
    24  		domainMap:   domainMap,
    25  		suffixList:  options.DomainSuffix,
    26  		keywordList: options.DomainKeyword,
    27  		regexList:   options.DomainRegex,
    28  	}
    29  	return rule, nil
    30  }
    31  
    32  func (r *searchGeositeMatcher) Match(domain string) string {
    33  	if r.domainMap[domain] {
    34  		return "domain=" + domain
    35  	}
    36  	for _, suffix := range r.suffixList {
    37  		if strings.HasSuffix(domain, suffix) {
    38  			return "domain_suffix=" + suffix
    39  		}
    40  	}
    41  	for _, keyword := range r.keywordList {
    42  		if strings.Contains(domain, keyword) {
    43  			return "domain_keyword=" + keyword
    44  		}
    45  	}
    46  	for _, regexStr := range r.regexList {
    47  		regex, err := regexp.Compile(regexStr)
    48  		if err != nil {
    49  			continue
    50  		}
    51  		if regex.MatchString(domain) {
    52  			return "domain_regex=" + regexStr
    53  		}
    54  	}
    55  	return ""
    56  }