Wrap errors and use cli library

master
Buddy Sandidge 8 years ago
parent 80a8c8044e
commit 7ae53c00d4

@ -3,16 +3,37 @@ package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"github.com/pkg/errors"
"github.com/urfave/cli"
)
func main() {
result, err := getIP("https://whatismyipv6.buddy.wtf/json")
app := cli.NewApp()
app.Name = "update-dns"
app.Usage = "update dnsimple with public ip address"
app.Action = action
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "url",
Value: "https://whatismyipv6.buddy.wtf/json",
Usage: "url to use to get public ip address",
},
}
app.Run(os.Args)
}
func action(context *cli.Context) error {
result, err := getIP(context.String("url"))
if err != nil {
log.Fatal(err)
return errors.Wrap(err, "could not get IP address")
}
fmt.Println(result.IP)
return nil
}
type whatIsMyIPResult struct {
@ -23,12 +44,12 @@ type whatIsMyIPResult struct {
func getIP(url string) (*whatIsMyIPResult, error) {
result, err := http.Get(url)
if err != nil {
return nil, err
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, err
return nil, errors.Wrap(err, "could parse json from url "+url)
}
return ipResult, nil
}

Loading…
Cancel
Save