-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
74 lines (61 loc) · 1.23 KB
/
main.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
package main
import (
"strings"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
)
const (
url = "http://ip-api.com/json/"
)
var commands = map[string]bool{
"query": true,
"city": true,
"country": true,
"countryCode": true,
"isp": true,
}
func main() {
apiClient := http.Client{
Timeout: time.Second * 2, // Maximum of 2 secs
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not create request!")
return
}
res, err := apiClient.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not get IP-API response! :(")
return
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not read json response!")
return
}
var ipResponse map[string]interface{}
err = json.Unmarshal([]byte(data), &ipResponse)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not parse json! :(")
return
}
if len(os.Args) != 2 {
fmt.Fprintln(os.Stdout, "Usage: ipinfo <cmd>")
os.Exit(1)
}
cmd := os.Args[1]
if strings.Compare(cmd, "ip") == 0 {
cmd = "query"
}
if !commands[cmd] {
fmt.Fprintf(os.Stderr, "%s is not a valid command\n", cmd)
os.Exit(1)
}
fmt.Printf("%s\n", ipResponse[cmd])
return
}