mirror of
https://github.com/zhigang1992/flora-kit.git
synced 2026-05-04 21:09:11 +08:00
实现 GeoIP 的路由规则;
This commit is contained in:
@@ -57,10 +57,11 @@ func init() {
|
||||
}
|
||||
iniConfig = cfg
|
||||
|
||||
loadGeoIP()
|
||||
loadProxy()
|
||||
loadRules()
|
||||
|
||||
debug.Println(RuleOfHost("www.google.com"))
|
||||
debug.Println("104.244.42.129", GeoIPString("104.244.42.129"))
|
||||
debug.Println(RuleOfHost("www.twitter.com"))
|
||||
}
|
||||
|
||||
@@ -139,28 +140,45 @@ func readArrayLine(source string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func RuleOfHost(host string) *DomainRule {
|
||||
func RuleOfHost(host string) (result *DomainRule) {
|
||||
result = &DomainRule{S: "", T: RULE_DIRECT}
|
||||
hostParts := strings.Split(host, ":")
|
||||
domain := hostParts[0]
|
||||
|
||||
for _, rule := range ruleSuffixDomains {
|
||||
if strings.HasSuffix(domain, rule.S) {
|
||||
return rule
|
||||
result = rule
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for _, rule := range rulePrefixDomains {
|
||||
if strings.HasPrefix(domain, rule.S) {
|
||||
return rule
|
||||
result = rule
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for _, rule := range ruleKeywordDomains {
|
||||
if strings.Contains(domain, rule.S) {
|
||||
return rule
|
||||
result = rule
|
||||
return
|
||||
}
|
||||
}
|
||||
return &DomainRule{S: "", T: RULE_DIRECT}
|
||||
|
||||
ips, err := net.LookupIP(host)
|
||||
if err != nil || len(ips) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
country := GeoIPs(ips)
|
||||
log.Println("Found ip geo", country)
|
||||
if len(country) != 0 && ruleGeoIP.S == country {
|
||||
result = ruleGeoIP
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func parseServerConfig() {
|
||||
|
||||
@@ -1,26 +1,40 @@
|
||||
package flora
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"log"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var geoDB *geoip2.Reader
|
||||
|
||||
func init() {
|
||||
func loadGeoIP() {
|
||||
file := "./geoip.mmdb"
|
||||
db, err := geoip2.Open(file)
|
||||
defer db.Close()
|
||||
// defer db.Close()
|
||||
if err != nil {
|
||||
fmt.Printf("Could not open GeoIP database\n")
|
||||
log.Printf("Could not open GeoIP database\n")
|
||||
}
|
||||
// log.Println("GeoIP inited.")
|
||||
geoDB = db
|
||||
}
|
||||
|
||||
func GeoIP(ipaddr string) string {
|
||||
func GeoIPString(ipaddr string) string {
|
||||
ip := net.ParseIP(ipaddr)
|
||||
return GeoIP(ip)
|
||||
}
|
||||
|
||||
func GeoIPs(ips []net.IP) string {
|
||||
if len(ips) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return GeoIP(ips[0])
|
||||
}
|
||||
|
||||
func GeoIP(ip net.IP) string {
|
||||
// log.Println("Lookup GEO IP", ip)
|
||||
country, err := geoDB.Country(ip)
|
||||
if err != nil {
|
||||
return ""
|
||||
|
||||
Reference in New Issue
Block a user