You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.2 KiB
Go

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
}