ソースを参照

added asn lookup

Tobias von Dewitz 5 年 前
コミット
8d318dfe06
1 ファイル変更16 行追加0 行削除
  1. 16 0
      setup.go

+ 16 - 0
setup.go

@@ -8,6 +8,8 @@ import (
 	"strconv"
 	"strings"
 
+	"git.scraperwall.com/scw/asndb"
+
 	"github.com/mholt/caddy"
 	"github.com/mholt/caddy/caddyhttp/httpserver"
 	"github.com/mmcloughlin/geohash"
@@ -18,6 +20,7 @@ import (
 type GeoIP struct {
 	Next      httpserver.Handler
 	DBHandler *maxminddb.Reader
+	ASNDB     *asndb.ASNDB
 	Config    Config
 }
 
@@ -39,6 +42,8 @@ type GeoIPRecord struct {
 		Longitude float64 `maxminddb:"longitude"`
 		TimeZone  string  `maxminddb:"time_zone"`
 	} `maxminddb:"location"`
+
+	ASN asndb.ASN
 }
 
 // Init initializes the plugin
@@ -59,11 +64,18 @@ func setup(c *caddy.Controller) error {
 	if err != nil {
 		return c.Err("geoip: Can't open database: " + config.DatabasePath)
 	}
+
+	asndb, err := asndb.New()
+	if err != nil {
+		return c.Err("asndb: failed to load: " + err.Error)
+	}
+
 	// Create new middleware
 	newMiddleWare := func(next httpserver.Handler) httpserver.Handler {
 		return &GeoIP{
 			Next:      next,
 			DBHandler: dbhandler,
+			ASNDB:     asndb,
 			Config:    config,
 		}
 	}
@@ -83,6 +95,8 @@ func (gip GeoIP) lookupLocation(w http.ResponseWriter, r *http.Request) {
 	record := gip.fetchGeoipData(r)
 
 	replacer := newReplacer(r)
+	replacer.Set("asn_asn", record.ASN.ASN)
+	replacer.Set("asn_organization", record.ASN.Organization)
 	replacer.Set("geoip_country_code", record.Country.ISOCode)
 	replacer.Set("geoip_country_name", record.Country.Names["en"])
 	replacer.Set("geoip_country_eu", strconv.FormatBool(record.Country.IsInEuropeanUnion))
@@ -108,6 +122,8 @@ func (gip GeoIP) fetchGeoipData(r *http.Request) GeoIPRecord {
 		log.Println(err)
 	}
 
+	record.ASN = gip.ASNDB.Lookup(clientIP)
+
 	if record.Country.ISOCode == "" {
 		record.Country.Names = make(map[string]string)
 		record.City.Names = make(map[string]string)