summaryrefslogtreecommitdiff
path: root/main.go
blob: 1c00d143b9123619d8edf37ea863cdb51ec1f131 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
	"strconv"

	"github.com/oschwald/geoip2-golang"
)

type geodb struct {
	db *geoip2.Reader
}

func floatToString(num float64) string {
	return strconv.FormatFloat(num, 'f', 6, 64)
}

func (g *geodb) getRecordForIP(ipstr string) *geoip2.City {
	ip := net.ParseIP(ipstr)
	record, err := g.db.City(ip)
	if err != nil {
		log.Fatal(err)
	}
	return record
}

type jsonHandler struct {
	geoipdb *geodb
}

func (jh *jsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	ip, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		log.Fatal(err)
	}
	netIP := net.ParseIP(ip)
	ipstr := netIP.String()
	record := jh.geoipdb.getRecordForIP(ipstr)
	data := map[string]string{
		"ip":   ipstr,
		"cc":   record.Country.IsoCode,
		"city": record.City.Names["en"],
		"lat":  floatToString(record.Location.Latitude),
		"lon":  floatToString(record.Location.Longitude),
	}
	dataJSON, _ := json.Marshal(data)
	fmt.Fprintf(w, string(dataJSON))
}

type txtHandler struct {
	geoipdb *geodb
}

func (th *txtHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	ip, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		log.Fatal(err)
	}
	netIP := net.ParseIP(ip)
	ipstr := netIP.String()
	record := th.geoipdb.getRecordForIP(ipstr)

	fmt.Fprintf(w, "Your IP: %s\n", ipstr)
	fmt.Fprintf(w, "Your Country: %s\n", record.Country.IsoCode)
	fmt.Fprintf(w, "Your City: %s\n", record.City.Names["en"])
	fmt.Fprintf(w, "Your Coordinates: %s, %s\n",
        floatToString(record.Location.Latitude),
		floatToString(record.Location.Longitude))
}

func main() {
	db, err := geoip2.Open("/var/lib/GeoIP/GeoLite2-City.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	geoipdb := geodb{db}

	mux := http.NewServeMux()
	jh := &jsonHandler{&geoipdb}
	mux.Handle("/json", jh)

	th := &txtHandler{&geoipdb}
	mux.Handle("/", th)

	log.Println("Listening...")
	http.ListenAndServe(":9001", mux)
}