-
Notifications
You must be signed in to change notification settings - Fork 77
/
geoip.go
75 lines (70 loc) · 1.61 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
69
70
71
72
73
74
75
package main
import (
"log"
"net"
"net/http"
"strings"
"github.com/gobuffalo/packr"
"github.com/oschwald/geoip2-golang"
)
var (
geoipBytes []byte
geoip *geoip2.Reader
)
func initGeoIP() {
var err error
box := packr.NewBox("../ui")
geoipBytes, err = box.Find("site/GeoLite2-Country.mmdb")
if err != nil {
log.Fatalf("Failed to load geoip database file")
return
}
geoip, err = geoip2.FromBytes(geoipBytes)
if err != nil {
log.Fatalf("Failed to load geoip database")
return
}
//captchaKey = h
}
func getCountry(r *http.Request) string {
userIP := ""
//log.Printf("Headers %v", r.Header)
if len(r.Header.Get("CF-Connecting-IP")) > 1 {
userIP = strings.TrimSpace(r.Header.Get("CF-Connecting-IP"))
}
if len(r.Header.Get("X-Forwarded-For")) > 1 && len(userIP) == 0 {
userIP = strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
}
if len(r.Header.Get("X-Real-IP")) > 1 && len(userIP) == 0 {
userIP = strings.TrimSpace(r.Header.Get("X-Real-IP"))
}
if len(userIP) == 0 {
userIP = r.RemoteAddr
}
if strings.Contains(userIP, ",") {
userIP = strings.Split(userIP, ",")[0]
}
if strings.Contains(userIP, " ") {
userIP = strings.Split(userIP, " ")[0]
}
if len(userIP) == 0 {
return ""
}
ip := net.ParseIP(userIP)
if ip == nil {
if strings.Count(userIP, ":") == 1 {
userIP = strings.Split(userIP, ":")[0]
ip = net.ParseIP(userIP)
}
if ip == nil {
log.Printf("Failed to parse userIP: %s", userIP)
return ""
}
}
record, err := geoip.Country(ip)
if err != nil {
log.Printf("Failed to detect country using IP address: %s", userIP)
return ""
}
return record.Country.IsoCode
}