예제 #1
0
// ExampleNestedStruct creates a Etcd directory using a nested Go struct and then gets the directory as JSON.
func Example_nestedStruct() {
	verbose := flag.Bool("verbose", false, "Verbose")
	node := flag.String("node", "", "Etcd node")
	port := flag.String("port", "", "Etcd port")
	flag.Parse()

	// Define nested structure.
	g := Group{
		Name: "staff",
		Users: []User{
			User{
				Name:      "jdoe",
				Age:       25,
				Male:      true,
				FirstName: "John",
				LastName:  "Doe",
			},
			User{
				Name:      "lnemoy",
				Age:       62,
				Male:      true,
				FirstName: "Leonard",
				LastName:  "Nimoy",
			},
		},
	}

	// Connect to Etcd.
	conn := getEnv()
	if node == nil && port == nil {
		conn = []string{fmt.Sprintf("http://%v:%v", *node, *port)}
	}

	if *verbose {
		log.Printf("Connecting to: %s", conn)
	}
	client := etcd.NewClient(conn)

	// Create directory structure based on struct.
	err := etcdmap.Create(client, "/example", reflect.ValueOf(g))
	if err != nil {
		log.Fatal(err.Error())
	}

	// Get directory structure from Etcd.
	res, err := client.Get("/example", true, true)
	if err != nil {
		log.Fatal(err.Error())
	}

	j, err2 := etcdmap.JSON(res.Node)
	if err2 != nil {
		log.Fatal(err2.Error())
	}

	fmt.Println(string(j))

	// Output:
	//{"id":"staff","users":{"0":{"age":"25","first_name":"John","id":"jdoe","last_name":"Doe","male":"true"},"1":{"age":"62","first_name":"Leonard","id":"lnemoy","last_name":"Nimoy","male":"true"}}}
}
예제 #2
0
파일: etcd.go 프로젝트: mickep76/etcdrest
// Put document.
func (s *session) Put(p string, d interface{}) (int, error) {
	if err := etcdmap.Create(s.keysAPI, p, reflect.ValueOf(d)); err != nil {
		return http.StatusInternalServerError, err
	}

	return http.StatusOK, nil
}
예제 #3
0
func importFunc(dir string, file string, f iodatafmt.DataFmt, replace bool, yes bool, e Etcdtool, c *cli.Context, ki client.KeysAPI) {
	// Check if dir exists and is a directory.
	exists, err := dirExists(dir, c, ki)
	if err != nil {
		fatalf("Specified dir doesn't exist: %s", dir)
	}

	if exists {
		exist, err := isDir(dir, c, ki)
		if err != nil {
			fatal(err.Error())
		}

		if exist {
			fatalf("Specified dir is not a directory: %s", dir)
		}
	}

	// Load file.
	m, err := iodatafmt.Load(file, f)
	if err != nil {
		fatal(err.Error())
	}

	// Validate data.
	if c.Bool("validate") {
		validateFunc(e, dir, m)
	}

	if exists {
		if replace {
			if !askYesNo(fmt.Sprintf("Do you want to overwrite data in directory: %s", dir)) {
				os.Exit(1)
			}

			// Delete dir.
			if _, err = ki.Delete(context.TODO(), dir, &client.DeleteOptions{Recursive: true}); err != nil {
				fatal(err.Error())
			}
		} else {
			if !yes {
				if !askYesNo(fmt.Sprintf("Do you want to overwrite data in directory: %s", dir)) {
					os.Exit(1)
				}
			}
		}
	} else {
		// Create dir.
		if _, err := ki.Set(context.TODO(), dir, "", &client.SetOptions{Dir: true}); err != nil {
			fatal(err.Error())
		}
	}

	// Import data.
	if err = etcdmap.Create(ki, dir, reflect.ValueOf(m)); err != nil {
		fatal(err.Error())
	}
}
예제 #4
0
func main() {
	// Get the FileInfo struct describing the standard input.
	fi, _ := os.Stdin.Stat()

	// Get connection env variable.
	conn := common.GetEnv()

	// Options.
	version := flag.Bool("version", false, "Version")
	force := flag.Bool("force", false, "Force delete without asking")
	delete := flag.Bool("delete", false, "Delete entry before import")
	node := flag.String("node", "", "Etcd node")
	port := flag.String("port", "2379", "Etcd port")
	dir := flag.String("dir", "", "Etcd directory")
	format := flag.String("format", "JSON", "Data serialization format YAML, TOML or JSON")
	input := flag.String("input", "", "Input file")
	flag.Parse()

	// Print version.
	if *version {
		fmt.Printf("etcd-import %s\n", common.Version)
		os.Exit(0)
	}

	// Validate input.
	if len(conn) < 1 && *node == "" {
		log.Fatalf("You need to specify Etcd host.")
	}

	if *dir == "" {
		log.Fatalf("You need to specify Etcd dir.")
	}

	// Get data format.
	f, err := iodatafmt.Format(*format)
	if err != nil {
		log.Fatal(err.Error())
	}

	// Setup Etcd client.
	if *node != "" {
		conn = []string{fmt.Sprintf("http://%v:%v", *node, *port)}
	}
	client := etcd.NewClient(conn)

	// Import data.
	var m interface{}
	if (fi.Mode() & os.ModeCharDevice) == 0 {
		b, _ := ioutil.ReadAll(os.Stdin)
		var err error
		m, err = iodatafmt.Unmarshal(b, f)
		if err != nil {
			log.Fatal(err.Error())
		}
	} else if *input != "" {
		var err error
		m, err = iodatafmt.Load(*input, f)
		if err != nil {
			log.Fatal(err.Error())
		}
	} else {
		log.Fatal("No input provided")
	}

	if *delete {
		if !*force {
			fmt.Printf("Remove path: %s? [yes|no]", strings.TrimRight(*dir, "/"))
			var query string
			fmt.Scanln(&query)
			if query != "yes" {
				os.Exit(0)
			}
		}

		if _, err := client.Delete(strings.TrimRight(*dir, "/"), true); err != nil {
			log.Fatalf(err.Error())
		}
		log.Printf("Removed path: %s", strings.TrimRight(*dir, "/"))
	}

	if err = etcdmap.Create(client, strings.TrimRight(*dir, "/"), reflect.ValueOf(m)); err != nil {
		log.Fatal(err.Error())
	}
}
예제 #5
0
// ExampleNestedStruct creates a Etcd directory using a nested Go struct and then gets the directory as JSON.
func Example_nestedStruct() {
	// Get env variables.
	env := getEnv()

	// Options.
	peers := flag.String("peers", env.Peers, "Comma separated list of etcd nodes, can be set with env. variable ETCD_PEERS")
	flag.Parse()

	// Define nested structure.
	g := Group{
		Name: "staff",
		Users: []User{
			User{
				Name:      "jdoe",
				Age:       25,
				Male:      true,
				FirstName: "John",
				LastName:  "Doe",
			},
			User{
				Name:      "lnemoy",
				Age:       62,
				Male:      true,
				FirstName: "Leonard",
				LastName:  "Nimoy",
			},
		},
	}

	// Connect to etcd.
	cfg := etcd.Config{
		Endpoints:               strings.Split(*peers, ","),
		Transport:               etcd.DefaultTransport,
		HeaderTimeoutPerRequest: time.Second,
	}

	client, err := etcd.New(cfg)
	if err != nil {
		log.Fatal(err)
	}

	kapi := etcd.NewKeysAPI(client)

	// Create directory structure based on struct.
	err2 := etcdmap.Create(kapi, "/example", reflect.ValueOf(g))
	if err2 != nil {
		log.Fatal(err2.Error())
	}

	// Get directory structure from Etcd.
	res, err3 := kapi.Get(context.TODO(), "/example", &etcd.GetOptions{Recursive: true})
	if err3 != nil {
		log.Fatal(err3.Error())
	}

	j, err4 := etcdmap.JSON(res.Node)
	if err4 != nil {
		log.Fatal(err4.Error())
	}

	fmt.Println(string(j))

	// Get directory structure from Etcd.
	/*
		res, err5 := kapi.Get(context.TODO(), "/example/users/0", &etcd.GetOptions{Recursive: true})
		if err5 != nil {
			log.Fatal(err5.Error())
		}

		s := User{}
		err6 := etcdmap.Struct(res.Node, reflect.ValueOf(&s))
		if err6 != nil {
			log.Fatal(err6.Error())
		}

		fmt.Println(s)
	*/

	// Output:
	//{"name":"staff","users":{"0":{"age":"25","first_name":"John","last_name":"Doe","male":"true","name":"jdoe"},"1":{"age":"62","first_name":"Leonard","last_name":"Nimoy","male":"true","name":"lnemoy"}}}
}