-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathip2country.go
59 lines (52 loc) · 1.24 KB
/
ip2country.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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"github.com/gorilla/handlers"
geoip2 "github.com/oschwald/geoip2-golang"
)
var dbFile = "GeoIP2-Country.mmdb"
func handler(w http.ResponseWriter, r *http.Request) {
db, err := geoip2.Open(dbFile)
if err != nil {
log.Fatal(err)
}
defer db.Close()
var ipAddr = r.URL.Path[1:]
if ipAddr == "" {
errorHandler(w, r, http.StatusNotFound, "IP is Null")
return
}
ip := net.ParseIP(ipAddr)
if ip == nil {
errorHandler(w, r, http.StatusNotFound, "Not Valid IP")
return
}
record, err := db.City(ip)
if err != nil {
errorHandler(w, r, 500, "Internal Server Error")
return
}
resp := make(map[string]string, 2)
resp["country"] = record.Country.Names["en"]
resp["code"] = record.Country.IsoCode
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func main() {
if _, err := os.Stat(dbFile); os.IsNotExist(err) {
log.Fatal(err)
}
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, http.DefaultServeMux)))
}
func errorHandler(w http.ResponseWriter, r *http.Request, status int, msg string) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, msg)
}
}