-
Notifications
You must be signed in to change notification settings - Fork 0
/
get.go
77 lines (64 loc) · 1.6 KB
/
get.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
package publicip
import (
"net"
"strings"
"gopkg.in/resty.v1"
)
var mirrors = []string{
"https://api.ipify.org",
"https://ifconfig.me",
"https://icanhazip.com",
"https://ipecho.net/plain",
"https://ifconfig.co",
}
// DefaultUserAgent is the user agent which will be used for connection.
// Note: changing this value may affect the result with some providers.
var DefaultUserAgent = "curl/7.58.0"
//Debug requests
var Debug = false
// HttpClient is a placehold for alternative http client.
// If it's not set (equal nil), then new client instance is generated for
// every request
var HttpClient *resty.Client
// SetMirrors permit to override 3d party ip resolvers used in this library (if for some reason you want to
// use your own)
func SetMirrors(newUrls []string) {
mirrors = newUrls
}
func Get() (string, error) {
var pubIp string
var err error
client := HttpClient
if client == nil {
client = resty.New()
client.SetDebug(Debug)
client.SetHeader("User-Agent", DefaultUserAgent)
}
for _, url := range mirrors {
pubIp, err = download(client, url)
if err == nil {
return pubIp, nil
}
}
return "", MirrorsExausted{}
}
func download(cl *resty.Client, url string) (string, error) {
resp, err := cl.R().
Get(url)
//check for errors and valid response
if err != nil {
return "", err
}
if resp.StatusCode() != 200 {
return "", DownloadError{
StatusCode: resp.StatusCode(),
Body: resp.Body(),
Url: url,
}
}
pubIp := strings.TrimSpace(string(resp.Body()))
if net.ParseIP(pubIp) == nil {
return "", InvalidResponseError{Response: pubIp}
}
return pubIp, nil
}