Skip to content

Instantly share code, notes, and snippets.

@aeden

aeden/myapp.go Secret

Created October 5, 2016 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeden/1a9e96e91ed05da85b7c248c6ea1d86e to your computer and use it in GitHub Desktop.
Save aeden/1a9e96e91ed05da85b7c248c6ea1d86e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/dnsimple/dnsimple-go/dnsimple"
)
func main() {
oauthToken := os.Getenv("TOKEN")
client := dnsimple.NewClient(dnsimple.NewOauthTokenCredentials(oauthToken))
listDomains := buildListDomainsFunc(client)
createDomain := buildCreateDomainFunc(client)
commands := map[string]func(string, map[string]string){
"domains.list": listDomains,
"domains.create": createDomain,
}
if len(os.Args) <= 1 {
usage("")
return
}
commandName := os.Args[1]
commandFunc := commands[commandName]
if commandFunc == nil {
usage(commandName)
} else {
fmt.Printf("Connecting to DNSimple API...\n\n")
whoamiResponse, err := client.Identity.Whoami()
if err != nil {
fmt.Printf("Whoami() returned error: %v\n", err)
os.Exit(1)
}
fmt.Printf("Connected as %+v\n\n", whoamiResponse.Data.Account.Email)
accountId := strconv.Itoa(whoamiResponse.Data.Account.ID)
commandFunc(accountId, extractOptions(os.Args))
}
}
func usage(commandName string) {
if commandName == "" {
fmt.Printf("Command is required\n\n")
} else {
fmt.Printf("Unknown command: %v\n\n", commandName)
}
fmt.Printf("The following commands are supported:\n")
fmt.Printf(" domains.list\n")
fmt.Printf(" domains.create name:example.com\n")
}
func buildListDomainsFunc(client *dnsimple.Client) func(string, map[string]string) {
return func(accountId string, _options map[string]string) {
listDomainsResponse, err := client.Domains.ListDomains(accountId, nil)
if err != nil {
fmt.Printf("ListDomains() returned error: %v\n", err)
os.Exit(1)
}
for _, domain := range listDomainsResponse.Data {
fmt.Printf("%+v\n", domain)
}
}
}
func buildCreateDomainFunc(client *dnsimple.Client) func(string, map[string]string) {
return func(accountId string, options map[string]string) {
domainAttributes := dnsimple.Domain{Name: options["name"]}
createDomainResponse, err := client.Domains.CreateDomain(accountId, domainAttributes)
if err != nil {
fmt.Printf("CreateDomain() returned error: %v\n", err)
os.Exit(1)
}
fmt.Printf("%+v\n", createDomainResponse.Data)
}
}
func extractOptions(args []string) map[string]string {
options := map[string]string{}
if len(args) > 2 {
for _, arg := range args[2:] {
argNameVal := strings.Split(arg, ":")
options[argNameVal[0]] = argNameVal[1]
}
}
return options
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment