-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
76 lines (63 loc) · 1.6 KB
/
main.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/oschwald/geoip2-golang"
"github.com/gorilla/mux"
"log"
"net"
"net/http"
)
var cityDatabase *geoip2.Reader
var countryDatabase *geoip2.Reader
var asnDatabase *geoip2.Reader
func main() {
fmt.Println("Starting server")
cityDatabase, _ = loadDatabase("City")
countryDatabase, _ = loadDatabase("Country")
asnDatabase, _ = loadDatabase("ASN")
r := mux.NewRouter()
r.HandleFunc("/{database}/{address}", geoIPHandler)
err := http.ListenAndServe(":80", r)
if err != nil {
log.Fatal(err.Error())
}
}
func geoIPHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
address := net.ParseIP(vars["address"])
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var ip interface{}
var err error
switch database := vars["database"]; database {
case "asn":
ip, err = asnDatabase.ASN(address)
case "city":
ip, err = cityDatabase.City(address)
case "country":
ip, err = countryDatabase.Country(address)
default:
_, _ = fmt.Fprintln(w, "Unknown database")
w.WriteHeader(http.StatusNotFound)
return
}
if err != nil {
_,_ = fmt.Fprintln(w, "IP not found")
w.WriteHeader(http.StatusNotFound)
return
}
ipJSON, err := json.Marshal(ip)
if err != nil {
log.Fatal("Cannot encode to JSON ", err)
w.WriteHeader(http.StatusInternalServerError)
}
_, _ = fmt.Fprint(w, string(ipJSON))
}
func loadDatabase(name string) (database *geoip2.Reader, err error){
db, err := geoip2.Open("data/GeoLite2-" + name + ".mmdb")
if err != nil {
return nil, errors.New("can't work with it")
}
return db, nil
}