实现 GeoIP 的路由规则;

This commit is contained in:
Jason Lee
2016-11-15 21:50:08 +08:00
parent 07906ed032
commit a697012487
2 changed files with 43 additions and 11 deletions

View File

@@ -57,10 +57,11 @@ func init() {
} }
iniConfig = cfg iniConfig = cfg
loadGeoIP()
loadProxy() loadProxy()
loadRules() loadRules()
debug.Println(RuleOfHost("www.google.com")) debug.Println("104.244.42.129", GeoIPString("104.244.42.129"))
debug.Println(RuleOfHost("www.twitter.com")) debug.Println(RuleOfHost("www.twitter.com"))
} }
@@ -139,28 +140,45 @@ func readArrayLine(source string) []string {
return out return out
} }
func RuleOfHost(host string) *DomainRule { func RuleOfHost(host string) (result *DomainRule) {
result = &DomainRule{S: "", T: RULE_DIRECT}
hostParts := strings.Split(host, ":") hostParts := strings.Split(host, ":")
domain := hostParts[0] domain := hostParts[0]
for _, rule := range ruleSuffixDomains { for _, rule := range ruleSuffixDomains {
if strings.HasSuffix(domain, rule.S) { if strings.HasSuffix(domain, rule.S) {
return rule result = rule
return
} }
} }
for _, rule := range rulePrefixDomains { for _, rule := range rulePrefixDomains {
if strings.HasPrefix(domain, rule.S) { if strings.HasPrefix(domain, rule.S) {
return rule result = rule
return
} }
} }
for _, rule := range ruleKeywordDomains { for _, rule := range ruleKeywordDomains {
if strings.Contains(domain, rule.S) { 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() { func parseServerConfig() {

View File

@@ -1,26 +1,40 @@
package flora package flora
import ( import (
"fmt"
"github.com/oschwald/geoip2-golang" "github.com/oschwald/geoip2-golang"
"log"
"net" "net"
"strings" "strings"
) )
var geoDB *geoip2.Reader var geoDB *geoip2.Reader
func init() { func loadGeoIP() {
file := "./geoip.mmdb" file := "./geoip.mmdb"
db, err := geoip2.Open(file) db, err := geoip2.Open(file)
defer db.Close() // defer db.Close()
if err != nil { 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 geoDB = db
} }
func GeoIP(ipaddr string) string { func GeoIPString(ipaddr string) string {
ip := net.ParseIP(ipaddr) 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) country, err := geoDB.Country(ip)
if err != nil { if err != nil {
return "" return ""