Refactor to add ip package

master
Buddy Sandidge 8 years ago
parent f05b4b4278
commit e151e3dbfd

@ -0,0 +1,55 @@
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
}

@ -1,13 +1,12 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"net/http"
"os" "os"
"sync" "sync"
"git.xbudex.com/buddy/update-dns/dns" "git.xbudex.com/buddy/update-dns/dns"
"git.xbudex.com/buddy/update-dns/ip"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/urfave/cli" "github.com/urfave/cli"
@ -52,16 +51,20 @@ func action(context *cli.Context) error {
host := context.Args().Get(0) host := context.Args().Get(0)
wg.Add(1) wg.Add(1)
ipClient := &ip.Client{
URLv4: "https://whatismyipv4.buddy.wtf/json",
URLv6: "https://whatismyipv6.buddy.wtf/json",
}
var getIPError error var getIPError error
var ip string var ip string
go func() { go func() {
defer wg.Done() defer wg.Done()
result, err := getIP(context.String("url")) if result, err := ipClient.GetIPv6(); err != nil {
if err != nil {
getIPError = errors.Wrap(err, "could not get IP address") getIPError = errors.Wrap(err, "could not get IP address")
return } else {
ip = result
} }
ip = result.IP
}() }()
client := dns.New(context.String("dnsimple-token")) client := dns.New(context.String("dnsimple-token"))
@ -113,21 +116,3 @@ func action(context *cli.Context) error {
return nil return nil
} }
type whatIsMyIPResult struct {
IP string `json:ip`
Version string `json:version`
}
func getIP(url string) (*whatIsMyIPResult, error) {
result, err := http.Get(url)
if err != nil {
return nil, errors.Wrap(err, "could not get url "+url)
}
defer result.Body.Close()
ipResult := &whatIsMyIPResult{}
if err := json.NewDecoder(result.Body).Decode(ipResult); err != nil {
return nil, errors.Wrap(err, "could parse json from url "+url)
}
return ipResult, nil
}

Loading…
Cancel
Save