-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.go
62 lines (49 loc) · 1.12 KB
/
api.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
type Response struct {
IP string `json:"Query"`
Status string
Country string
CountryCode string
Region string
RegionName string
City string
Timezone string
Isp string
Org string
As string
Asname string
Proxy bool
}
func get_from_api(ip string) Response {
url := "http://ip-api.com/json/" + ip + "?fields=status,message,country,countryCode,region,regionName,city,timezone,isp,org,as,asname,proxy,query"
spaceClient := http.Client{
Timeout: time.Second * 20, // Timeout after 2 seconds
}
req, reqErr := http.NewRequest(http.MethodGet, url, nil)
if reqErr != nil {
return Response{IP: ip}
}
res, getErr := spaceClient.Do(req)
if getErr != nil {
return Response{IP: ip}
}
if res.Body != nil {
defer res.Body.Close()
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return Response{IP: ip}
}
apiResponse := Response{}
jsonErr := json.Unmarshal(body, &apiResponse)
if jsonErr != nil {
return Response{IP: ip}
}
return apiResponse
}