master
 1package get
 2
 3import (
 4	"context"
 5	"fmt"
 6
 7	"github.com/carlmjohnson/requests"
 8	"github.com/kahnwong/swissknife/configs/color"
 9	"github.com/kahnwong/swissknife/internal/utils"
10)
11
12type IPInfoResponse struct {
13	Query       string  `json:"query"`
14	Status      string  `json:"status"`
15	Country     string  `json:"country"`
16	CountryCode string  `json:"countryCode"`
17	Region      string  `json:"region"`
18	RegionName  string  `json:"regionName"`
19	City        string  `json:"city"`
20	Zip         string  `json:"zip"`
21	Lat         float64 `json:"lat"`
22	Lon         float64 `json:"lon"`
23	Timezone    string  `json:"timezone"`
24	Isp         string  `json:"isp"`
25	Org         string  `json:"org"`
26	As          string  `json:"as"`
27}
28
29func getIPInfo(ip string) (IPInfoResponse, error) {
30	var response IPInfoResponse
31	err := requests.
32		URL(fmt.Sprintf("http://ip-api.com/json/%s", ip)).
33		ToJSON(&response).
34		Fetch(context.Background())
35
36	if err != nil {
37		return IPInfoResponse{}, fmt.Errorf("error getting detailed ip info: %w", err)
38	}
39
40	return response, nil
41}
42
43func IPInfo(args []string) error {
44	ip := utils.SetIP(args)
45
46	var targetIP string
47	if ip == "" {
48		publicIP, err := getPublicIP()
49		if err != nil {
50			return err
51		}
52		targetIP = publicIP.Ip
53	} else {
54		targetIP = ip
55	}
56
57	ipInfo, err := getIPInfo(targetIP)
58	if err != nil {
59		return err
60	}
61
62	fmt.Printf("%s: %s\n", color.Green("IP Address"), ipInfo.Query)
63	fmt.Printf("%s: %s, %s, %s\n", color.Green("Location"), ipInfo.City, ipInfo.RegionName, color.Blue(ipInfo.Country))
64	fmt.Printf("%s: %s\n", color.Green("ISP"), ipInfo.Isp)
65	fmt.Printf("%s: %s\n", color.Green("Organization"), ipInfo.Org)
66	return nil
67}