github.com/metacubex/mihomo@v1.18.5/component/mmdb/reader.go (about)

     1  package mmdb
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"strings"
     7  
     8  	"github.com/oschwald/maxminddb-golang"
     9  )
    10  
    11  type geoip2Country struct {
    12  	Country struct {
    13  		IsoCode string `maxminddb:"iso_code"`
    14  	} `maxminddb:"country"`
    15  }
    16  
    17  type IPReader struct {
    18  	*maxminddb.Reader
    19  	databaseType
    20  }
    21  
    22  type ASNReader struct {
    23  	*maxminddb.Reader
    24  }
    25  
    26  type ASNResult struct {
    27  	AutonomousSystemNumber       uint32 `maxminddb:"autonomous_system_number"`
    28  	AutonomousSystemOrganization string `maxminddb:"autonomous_system_organization"`
    29  }
    30  
    31  func (r IPReader) LookupCode(ipAddress net.IP) []string {
    32  	switch r.databaseType {
    33  	case typeMaxmind:
    34  		var country geoip2Country
    35  		_ = r.Lookup(ipAddress, &country)
    36  		if country.Country.IsoCode == "" {
    37  			return []string{}
    38  		}
    39  		return []string{strings.ToLower(country.Country.IsoCode)}
    40  
    41  	case typeSing:
    42  		var code string
    43  		_ = r.Lookup(ipAddress, &code)
    44  		if code == "" {
    45  			return []string{}
    46  		}
    47  		return []string{code}
    48  
    49  	case typeMetaV0:
    50  		var record any
    51  		_ = r.Lookup(ipAddress, &record)
    52  		switch record := record.(type) {
    53  		case string:
    54  			return []string{record}
    55  		case []any: // lookup returned type of slice is []any
    56  			result := make([]string, 0, len(record))
    57  			for _, item := range record {
    58  				result = append(result, item.(string))
    59  			}
    60  			return result
    61  		}
    62  		return []string{}
    63  
    64  	default:
    65  		panic(fmt.Sprint("unknown geoip database type:", r.databaseType))
    66  	}
    67  }
    68  
    69  func (r ASNReader) LookupASN(ip net.IP) ASNResult {
    70  	var result ASNResult
    71  	r.Lookup(ip, &result)
    72  	return result
    73  }