diff options
Diffstat (limited to 'nccli.go')
| -rw-r--r-- | nccli.go | 95 |
1 files changed, 65 insertions, 30 deletions
@@ -15,7 +15,7 @@ import ( var ( verbose = false - url string + apiUrl string ) // Based on: https://www.namecheap.com/support/api/methods/domains-dns/set-hosts/ @@ -53,28 +53,44 @@ type Host struct { // Helper functions // -// Check if a env var is defined. If not defined, show error. +// Check if a env var is defined. If not defined, return error. // Args: key - the env var to check for. // Returns if exists, the value of the var. -func getEnv(key string) string { +func getEnv(key string) (string, error) { value := os.Getenv(key) if len(value) == 0 { - log.Fatalf("Env var %s is required and missing.", key) + return value, fmt.Errorf("Env var %s is required and missing.", key) } if verbose { fmt.Println(key, value) } - return value + return value, nil } -// Load ENV vars into the url var. -func loadConfig() { - url = "https://api.namecheap.com/xml.response?ApiUser=" + getEnv("API_USER") + - "&ApiKey=" + getEnv("API_KEY") + - "&UserName=" + getEnv("API_USER") + - "&ClientIp=" + getEnv("ACCESS_IP") + - "&SLD=" + getEnv("DOMAIN_MAIN") + - "&TLD=" + getEnv("DOMAIN_END") +// Load ENV vars into the apiUrl var. +// Returns nil if config loaded successfully, error otherwise. +func loadConfig() error { + keys := [5]string{"API_USER", "API_KEY", "ACCESS_IP", "DOMAIN_MAIN", "DOMAIN_END"} + for _, key := range keys { + _, err := getEnv(key) + if err != nil { + return err + } + } + user, _ := getEnv("API_USER") + apiKey, _ := getEnv("API_KEY") + accessIP, _ := getEnv("ACCESS_IP") + domainMain, _ := getEnv("DOMAIN_MAIN") + domainEnd, _ := getEnv("DOMAIN_END") + + apiUrl = "https://api.namecheap.com/xml.response?ApiUser=" + user + + "&ApiKey=" + apiKey + + "&UserName=" + user + + "&ClientIp=" + accessIP + + "&SLD=" + domainMain + + "&TLD=" + domainEnd + + return nil } // Print host recrods to stdout. @@ -96,17 +112,17 @@ func logRecords(hosts []Host) { // Make the API request to Namecheap. // Args: endPoint - the api method to call. -// extraParams (optional) - more params to add to the url. +// extraParams (optional) - more params to add to the apiUrl. // Returns the response byte stream. func makeReq(endPoint string, extraParams ...string) []byte { - apiUrl := url + "&Command=namecheap.domains.dns." + endPoint + methodUrl := apiUrl + "&Command=namecheap.domains.dns." + endPoint for _, param := range extraParams { - apiUrl += param + methodUrl += param } if verbose { - fmt.Println("Using api url:", apiUrl) + fmt.Println("Using api url:", methodUrl) } var ( @@ -115,9 +131,9 @@ func makeReq(endPoint string, extraParams ...string) []byte { ) switch endPoint { case "gethosts": - response, err = http.Get(apiUrl) + response, err = http.Get(methodUrl) case "sethosts": - response, err = http.Post(apiUrl, "application/xml", nil) + response, err = http.Post(methodUrl, "application/xml", nil) default: log.Fatalln("Error: Invalid request type specified.") } @@ -137,24 +153,27 @@ func makeReq(endPoint string, extraParams ...string) []byte { // Args: userChoicesStrs - slice of strings corresponding to user choices. // maxVal - the maximum int value allowed as input. // Returns the slice of integers. -func normalizeUserChoices(userChoicesStrs []string, maxVal int) []int { +func normalizeUserChoices(userChoicesStrs []string, maxVal int) ([]int, error) { var chosenInts []int for _, choice := range userChoicesStrs { - if len(strings.TrimSpace(choice)) == 0 { + text := strings.TrimSpace(choice) + if len(text) == 0 { continue } - val, err := strconv.Atoi(choice) + val, err := strconv.Atoi(text) if err != nil { - log.Fatalln("Error: Bad user input detected. Please only enter numbers.") + //log.Fatalln("Error: Bad user input detected. Please only enter numbers.") + return nil, fmt.Errorf("Error: Bad input detected: %s. Please only enter numbers.", text) } // validate if (val >= 0) && (val < maxVal) { chosenInts = append(chosenInts, val) } else { - log.Fatalln("Error: Bad user input detected. One of the numbers is not correct.") + //log.Fatalln("Error: Bad user input detected. One of the numbers is not correct.") + return nil, fmt.Errorf("Error: Bad user input detected. The number %d is out of range.", val) } } - return chosenInts + return chosenInts, nil } // Updates the hostRecords set with new data. @@ -296,7 +315,11 @@ func removeRecord() { // get user input for which ones to delete userChoicesStrs := userInputHandler() - userChoicesInts := normalizeUserChoices(userChoicesStrs, len(hostRecords)) + userChoicesInts, err := normalizeUserChoices(userChoicesStrs, len(hostRecords)) + if err != nil { + log.Fatalln(err) + } + // build the desired set of host records. var newHostRecords []Host @@ -375,25 +398,37 @@ func main() { switch os.Args[1] { case "list": listCmd.Parse(os.Args[2:]) - loadConfig() + err := loadConfig() + if err != nil { + log.Fatalln(err) + } logRecords(getAllRecords()) case "add": addCmd.Parse(os.Args[2:]) if *addName == "" || *addType == "" || *addAddress == "" { log.Fatalln(addUpdateErrorMsg) } - loadConfig() + err := loadConfig() + if err != nil { + log.Fatalln(err) + } addRecord(*addName, *addType, *addAddress, *addMXPref, *addTTL) case "remove": removeCmd.Parse(os.Args[2:]) - loadConfig() + err := loadConfig() + if err != nil { + log.Fatalln(err) + } removeRecord() case "update": updateCmd.Parse(os.Args[2:]) if *updateName == "" || *updateType == "" || *updateAddress == "" { log.Fatalln(addUpdateErrorMsg) } - loadConfig() + err := loadConfig() + if err != nil { + log.Fatalln(err) + } updateRecord(*updateName, *updateType, *updateAddress, *updateMXPref, *updateTTL) default: log.Fatalln(subCmdErrorMsg) |
