/
ipapi.go
57 lines (48 loc) · 1.29 KB
/
ipapi.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
package ipapi
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type Result struct {
As string `json:"as"`
City string `json:"city"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Isp string `json:"isp"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Org string `json:"org"`
Query string `json:"query"`
Region string `json:"region"`
RegionName string `json:"regionName"`
TimeZone string `json:"timezone"`
Zip string `json:"zip"`
}
const Endpoint = "http://ip-api.com/json"
var EnableQuery bool = true
var ErrQueryDisabled = errors.New("ipapi: Query disabled by user.")
func Query() (*Result, error) {
if !EnableQuery {
return nil, ErrQueryDisabled
}
resp, err := http.Get(Endpoint)
if err != nil {
return nil, fmt.Errorf("http.Get: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("non 200 response status: %s", resp.Status)
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("ioutil.ReadAll(resp.Body): %w", err)
}
var result Result
if err := json.Unmarshal(bs, &result); err != nil {
return nil, fmt.Errorf("json.Unmarshal: %w", err)
}
return &result, nil
}