-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip2geo.go
60 lines (52 loc) · 1.61 KB
/
ip2geo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"github.com/oschwald/geoip2-golang"
"log"
"net"
"net/http"
"encoding/json"
)
type whois struct{
City string
Country string
}
func listen(){
http.HandleFunc("/", ip2geo)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func ip2geo(w http.ResponseWriter, r *http.Request){
queryValues := r.URL.Query()
//fmt.Printf(string(myip[0]))
ipParam:=string(queryValues.Get("ip"));
//fmt.Fprintf(w, "hello, %s!\n", ipParam)
db, err := geoip2.Open("GeoLite2-City.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// If you are using strings that may be invalid, check that ip is not nil
if (ipParam!=""){
ip := net.ParseIP(ipParam)
record, err := db.City(ip)
if err != nil {
log.Fatal(err)
}
r:=whois{record.City.Names["pt-BR"],record.Country.Names["en"]}
jdata, err := json.Marshal(r)
fmt.Printf("%+v\n", r)
w.Header().Set("Content-Type", "application/json")
w.Write(jdata)
//fmt.Printf("Portuguese (BR) city name: %v\n", record.City.Names["pt-BR"])
//fmt.Printf("English subdivision name: %v\n", record.Subdivisions[0].Names["en"])
//fmt.Printf("Russian country name: %v\n", record.Country.Names["ru"])
//fmt.Printf("ISO country code: %v\n", record.Country.IsoCode)
//fmt.Printf("Time zone: %v\n", record.Location.TimeZone)
//fmt.Printf("Coordinates: %v, %v\n", record.Location.Latitude, record.Location.Longitude)
}
}
func main() {
listen();
}