geoip

short golang utility to fetch geoip data from an API
git clone https://git.parazyd.org/geoip
Log | Files | Refs | LICENSE

commit b5a354b3003d7f6a2d81b0441d8d476fb6393ffa
parent 21390e10b017149a5cef73d209d2929c4824c362
Author: parazyd <parazyd@dyne.org>
Date:   Mon, 29 Jul 2019 09:38:05 +0200

Add initial code.

Diffstat:
Ageoip.go | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 57 insertions(+), 0 deletions(-)

diff --git a/geoip.go b/geoip.go @@ -0,0 +1,57 @@ +package main + +/* See LICENSE file for copyright and license details */ + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "io/ioutil" + "log" + "net/http" + "os" + "strings" +) + +type Result struct { + //XMLName xml.Name `xml:"result"` + IP string `xml:"ip"` + Host string `xml:"host"` + ISP string `xml:"isp"` + City string `xml:"city"` + CountryCode string `xml:"countrycode"` + CountryName string `xml:"countryname"` + Latitude string `xml:"latitude"` + Longitude string `xml:"longitude"` +} + +func main() { + if len(os.Args) != 2 { + fmt.Fprintf(os.Stderr, "usage: geoip 1.1.1.1\n") + os.Exit(1) + } + + resp, err := http.Get("http://api.geoiplookup.net/?query=" + os.Args[1]) + if err != nil { + log.Fatal(err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + sbody := string(body) + sbody = strings.Replace(sbody, "iso-8859-1", "UTF-8", 1) + sbody = strings.Replace(sbody, "<ip>\n<results>", "", 1) + sbody = strings.Replace(sbody, "</results>\n</ip>", "", 1) + + var data Result + if err := xml.Unmarshal([]byte(sbody), &data); err != nil { + log.Fatal(err) + } + + enc := json.NewEncoder(os.Stdout) + enc.Encode(data) +}