-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
71 lines (57 loc) · 1.49 KB
/
handler.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
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net"
"net/http"
)
type Location struct {
Latitude float64 `json:"lat"`
Longitude float64 `json:"lng"`
}
type Country struct {
CountryCode string `json:"country_code" maxminddb:"iso_code"` // ISO 3166-1 alpha-2 2-letter country code
}
type MaxMindRecord struct {
Country Country `maxminddb:"country"`
}
func georeverseIPHandler(w http.ResponseWriter, r *http.Request) {
var record MaxMindRecord
vars := mux.Vars(r)
ip := net.ParseIP(vars["ipAddress"])
if ip == nil {
http.Error(w, "Invalid IP Address specified", http.StatusBadRequest)
return
}
err := geodb.Lookup(ip, &record)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(record.Country)
}
func georeverseHandler(w http.ResponseWriter, r *http.Request) {
var latlng Location
var results Country
w.Header().Set("Content-Type", "application/json")
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&latlng)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
results.CountryCode = reverser.GetCountryCode(latlng.Longitude, latlng.Latitude)
if results.CountryCode == "" {
log.Printf("Unable to decode country for %+v\n", latlng)
w.WriteHeader(http.StatusBadRequest)
return
}
err = json.NewEncoder(w).Encode(results)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}