duckdnsrefresh

Utility to refresh dyn hostnames from duckdns.org
git clone https://git.e1e0.net/duckdnsrefresh.git
Log | Files | Refs | README | LICENSE

main.go (1866B)


      1 //
      2 // main.go
      3 // Copyright (C) 2017 Paco Esteban <paco@onna.be>
      4 //
      5 // Distributed under terms of the MIT license.
      6 //
      7 
      8 package main
      9 
     10 import (
     11 	"flag"
     12 	"fmt"
     13 	"io/ioutil"
     14 	"log"
     15 	"net/http"
     16 	"os"
     17 
     18 	"github.com/spf13/viper"
     19 )
     20 
     21 var (
     22 	token   string
     23 	domains []string
     24 	Version string
     25 	Build   string
     26 )
     27 
     28 func main() {
     29 	var v = flag.Bool("v", false, "Enable verbose output")
     30 	var ver = flag.Bool("V", false, "Shows version and exists")
     31 	flag.Parse()
     32 
     33 	if *ver {
     34 		fmt.Printf("Version: %s. Build: %s\n", Version, Build)
     35 		os.Exit(0)
     36 	}
     37 	viper.SetConfigName("config")         // name of config file (without extension)
     38 	viper.AddConfigPath("/etc/duckdns/")  // path to look for the config file in
     39 	viper.AddConfigPath("$HOME/.duckdns") // call multiple times to add many search paths
     40 	viper.AddConfigPath(".")              // optionally look for config in the working directory
     41 	err := viper.ReadInConfig()           // Find and read the config file
     42 	if err != nil {                       // Handle errors reading the config file
     43 		panic(fmt.Errorf("Fatal error config file: %s \n", err))
     44 	}
     45 
     46 	token = viper.GetString("token")
     47 	domains = viper.GetStringSlice("domains")
     48 
     49 	for _, d := range domains {
     50 		if *v {
     51 			log.Printf("Trying to update domain: %s", d)
     52 		}
     53 		req := fmt.Sprintf("https://www.duckdns.org/update?domains=%s&token=%s", d, token)
     54 		r, err := http.Get(req)
     55 		if err != nil {
     56 			log.Fatalf("cannot get url: %s : %q", req, err)
     57 		}
     58 		if r.StatusCode != http.StatusOK {
     59 			log.Fatalf("incorrect response from server: %s ", r.Status)
     60 		}
     61 		defer r.Body.Close()
     62 
     63 		body, err := ioutil.ReadAll(r.Body)
     64 		if err != nil {
     65 			log.Fatalf("could not read the body: %q", err)
     66 		}
     67 		if string(body) != "OK" {
     68 			log.Fatalf("error while refreshing domain: %s", string(body))
     69 		}
     70 
     71 		if *v {
     72 			log.Printf("All good. got response '%s' from DuckDNS.", string(body))
     73 		}
     74 	}
     75 }