package ip import ( "encoding/json" "net/http" "github.com/pkg/errors" ) // IP address results type IP struct { IP string `json:ip` Version string `json:version` } // Client for getting IP address type Client struct { URLv4 string URLv6 string } // GetIPv6 returns an IPv6 IP address func (c *Client) GetIPv6() (string, error) { return c.getIP(c.URLv6, "v6") } // GetIPv4 returns an IPv6 IP address func (c *Client) GetIPv4() (string, error) { return c.getIP(c.URLv4, "v4") } // GetIPv6 returns an IPv6 IP address func (c *Client) getIP(host, version string) (string, error) { ip, err := c.fetchIP(host) if err != nil { return "", errors.Wrap(err, "could not get ip address") } if ip.Version != version { return "", errors.New("did not get " + version + " result") } return ip.IP, nil } func (c *Client) fetchIP(host string) (*IP, error) { result, err := http.Get(host) if err != nil { return nil, errors.Wrap(err, "could not get url "+host) } defer result.Body.Close() ipResult := &IP{} if err := json.NewDecoder(result.Body).Decode(ipResult); err != nil { return nil, errors.Wrap(err, "could parse json from url "+host) } return ipResult, nil }