-
Notifications
You must be signed in to change notification settings - Fork 204
/
countrychecker.go
90 lines (66 loc) · 1.98 KB
/
countrychecker.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package utils
import (
"context"
"encoding/json"
"log"
"net/http"
"strings"
"time"
)
// CheckCountry allows to check which country the app is running from
func CheckCountry(countriesToAvoid []string, strictCountryCheck bool) (bool, string) {
const maxFetchRetries = 3
var country, ip string
for retries := 1; ; retries++ {
log.Printf("Checking IP address, attempt #%d", retries)
var err error
if country, ip, err = fetchLocationInfo(); err != nil {
if retries < maxFetchRetries {
time.Sleep(time.Second)
continue
}
if strictCountryCheck {
log.Printf("Failed to check the country info in %d attempts while in strict mode", maxFetchRetries)
return false, ""
}
return true, ""
}
break
}
log.Printf("Current country: %s (%s)", country, ip)
for i := range countriesToAvoid {
if country == strings.TrimSpace(countriesToAvoid[i]) {
log.Println("You might need to enable VPN.")
openBrowser("https://arriven.github.io/db1000n/vpn/")
return !strictCountryCheck, country
}
}
return true, country
}
func fetchLocationInfo() (country, ip string, err error) {
const (
ipCheckerURI = "https://api.myip.com/"
requestTimeout = 3 * time.Second
)
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ipCheckerURI, nil)
if err != nil {
return "", "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Println("Can't check users country. Please manually check that VPN is enabled or that you have non Ukrainian IP address.")
return "", "", err
}
defer resp.Body.Close()
ipInfo := struct {
Country string `json:"country"`
IP string `json:"ip"`
}{}
if err := json.NewDecoder(resp.Body).Decode(&ipInfo); err != nil {
log.Println("Can't check users country. Please manually check that VPN is enabled or that you have non Ukrainian IP address.")
return "", "", err
}
return ipInfo.Country, ipInfo.IP, nil
}