Moved GeoIP module to utils package
This commit is contained in:
parent
c34943807f
commit
fcbee25fa0
|
@ -0,0 +1,81 @@
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
|
)
|
||||||
|
|
||||||
|
func HandleGeoIPCommand(ipAddress string, dbCity string, dbASN string) (string, error) {
|
||||||
|
ip := net.ParseIP(ipAddress)
|
||||||
|
|
||||||
|
// Check if IP/Hostname is valid
|
||||||
|
if ip == nil {
|
||||||
|
resolvedIP, err := net.LookupIP(ipAddress)
|
||||||
|
if err != nil || len(resolvedIP) == 0 {
|
||||||
|
return "", fmt.Errorf("Invalid IP or hostname: %s", ipAddress)
|
||||||
|
}
|
||||||
|
ip = resolvedIP[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
city = "N/A"
|
||||||
|
state = "N/A"
|
||||||
|
country = "N/A"
|
||||||
|
asn = "N/A"
|
||||||
|
isp = "N/A"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Lookup City, State and Country info
|
||||||
|
if cityDb, err := geoip2.Open(dbCity); err == nil {
|
||||||
|
defer cityDb.Close()
|
||||||
|
|
||||||
|
if cityRecord, err := cityDb.City(ip); err == nil {
|
||||||
|
if name := cityRecord.City.Names["en"]; name != "" {
|
||||||
|
city = name
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cityRecord.Subdivisions) > 0 {
|
||||||
|
if name := cityRecord.Subdivisions[0].Names["en"]; name != "" {
|
||||||
|
state = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if name := cityRecord.Country.Names["en"]; name != "" {
|
||||||
|
country = name
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return "", fmt.Errorf("City Lookup error: %v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return "", fmt.Errorf("Error opening City database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup ASN info
|
||||||
|
if asnDb, err := geoip2.Open(dbASN); err == nil {
|
||||||
|
defer asnDb.Close()
|
||||||
|
|
||||||
|
if asnRecord, err := asnDb.ASN(ip); err == nil {
|
||||||
|
if asnNum := asnRecord.AutonomousSystemNumber; asnNum != 0 {
|
||||||
|
asn = fmt.Sprintf("%d", asnNum)
|
||||||
|
}
|
||||||
|
|
||||||
|
if org := asnRecord.AutonomousSystemOrganization; org != "" {
|
||||||
|
isp = org
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return "", fmt.Errorf("ASN lookup error: %v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return "", fmt.Errorf("Error opening ASN database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format the response
|
||||||
|
response := fmt.Sprintf(
|
||||||
|
"IP: %s | Location: %s, %s, %s | ASN: %s | ISP: %s",
|
||||||
|
ip.String(), city, state, country, asn, isp,
|
||||||
|
)
|
||||||
|
|
||||||
|
return response, nil
|
||||||
|
}
|
Loading…
Reference in New Issue