add hostname lookup

This commit is contained in:
Thomas Wouters 2015-09-21 18:03:52 +02:00
parent ccd3c7a7bb
commit 3d14ea63ba
2 changed files with 19 additions and 7 deletions

View File

@ -21,6 +21,7 @@ import (
const (
IP_HEADER = "x-ifconfig-ip"
COUNTRY_HEADER = "x-ifconfig-country"
HOSTNAME_HEADER = "x-ifconfig-hostname"
TEXT_PLAIN = "text/plain; charset=utf-8"
APPLICATION_JSON = "application/json"
)
@ -28,9 +29,10 @@ const (
var cliUserAgentExp = regexp.MustCompile("^(?i)(curl|wget|fetch\\slibfetch)\\/.*$")
type API struct {
db *geoip2.Reader
CORS bool
Template string
db *geoip2.Reader
CORS bool
ReverseLookup bool
Template string
}
func New() *API { return &API{} }
@ -197,6 +199,14 @@ func (a *API) requestFilter(next http.Handler) http.Handler {
r.Header.Set(COUNTRY_HEADER, country)
}
}
if a.ReverseLookup {
hostname, err := net.LookupAddr(ip.String())
if err != nil {
r.Header.Set(HOSTNAME_HEADER, err.Error())
} else {
r.Header.Set(HOSTNAME_HEADER, strings.Join(hostname, ", "))
}
}
if a.CORS {
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Access-Control-Allow-Origin", "*")

10
main.go
View File

@ -11,10 +11,11 @@ import (
func main() {
var opts struct {
DBPath string `short:"f" long:"file" description:"Path to GeoIP database" value-name:"FILE" default:""`
Listen string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
CORS bool `short:"x" long:"cors" description:"Allow requests from other domains" default:"false"`
Template string `short:"t" long:"template" description:"Path to template" default:"index.html"`
DBPath string `short:"f" long:"file" description:"Path to GeoIP database" value-name:"FILE" default:""`
Listen string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
CORS bool `short:"x" long:"cors" description:"Allow requests from other domains" default:"false"`
ReverseLookup bool `short:"r" long:"reverselookup" description:"Perform reverse hostname lookups" default:"false"`
Template string `short:"t" long:"template" description:"Path to template" default:"index.html"`
}
_, err := flags.ParseArgs(&opts, os.Args)
if err != nil {
@ -32,6 +33,7 @@ func main() {
}
a.CORS = opts.CORS
a.ReverseLookup = opts.ReverseLookup
a.Template = opts.Template
log.Printf("Listening on %s", opts.Listen)