-
Notifications
You must be signed in to change notification settings - Fork 3
/
geoip.go
68 lines (52 loc) · 1.1 KB
/
geoip.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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/oschwald/geoip2-golang"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/city/{ip}", Lookup)
http.Handle("/", router)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func Lookup(w http.ResponseWriter, r *http.Request) {
// Basic Auth
username, password, ok := r.BasicAuth()
if os.Getenv("GEOIP_BASIC_AUTH") == "true" {
if !(ok &&
(username == os.Getenv("GEOIP_USERNAME")) &&
(password == os.Getenv("GEOIP_PASSWORD"))) {
http.Error(w, "Unauthorized", 401)
return
}
}
ipStr := mux.Vars(r)["ip"]
ip := net.ParseIP(ipStr)
if ip == nil {
http.Error(w, "IP address malformed", 400)
return
}
db, err := geoip2.Open("GeoLite2-City.mmdb")
if err != nil {
http.Error(w, "Server error", 500)
return
}
defer db.Close()
record, err := db.City(ip)
if err != nil {
http.Error(w, "Server error", 500)
return
}
j, err := json.Marshal(record)
if err != nil {
http.Error(w, "Server error", 500)
return
}
fmt.Fprintf(w, string(j))
}