etcd

package
v0.12.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2022 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package etcd allows the core package to bootstrap its configuration from an etcd server.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/DoNewsCode/core"
	"github.com/DoNewsCode/core/codec/yaml"
	"github.com/DoNewsCode/core/config/remote/etcd"
	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	addr := os.Getenv("ETCD_ADDR")
	if addr == "" {
		fmt.Println("set ETCD_ADDR for run example")
		return
	}
	key := "core.yaml"
	envEtcdAddrs := strings.Split(addr, ",")
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	cfg := clientv3.Config{
		Endpoints:   envEtcdAddrs,
		DialTimeout: time.Second,
		Context:     ctx,
	}
	_ = put(cfg, key, "name: etcd")

	c := core.New(etcd.WithKey(cfg, key, yaml.Codec{}))
	c.ProvideEssentials()
	fmt.Println(c.String("name"))

}

func put(cfg clientv3.Config, key, val string) error {
	client, err := clientv3.New(cfg)
	if err != nil {
		return err
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	_, err = client.Put(ctx, key, val)
	if err != nil {
		return err
	}

	return nil
}
Output:

etcd

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithKey

func WithKey(cfg clientv3.Config, key string, codec contract.Codec) (core.CoreOption, core.CoreOption)

WithKey is a two-in-one coreOption. It uses the remote key on etcd as the source of configuration, and watches the change of that key for hot reloading.

Types

type ETCD

type ETCD struct {
	// contains filtered or unexported fields
}

ETCD is a core.ConfProvider and contract.ConfigWatcher implementation to read and watch remote config key. The remote client uses etcd.

func Provider

func Provider(clientConfig clientv3.Config, key string) *ETCD

Provider create a *ETCD

func (*ETCD) Read

func (r *ETCD) Read() (map[string]interface{}, error)

Read is not supported by the remote provider.

func (*ETCD) ReadBytes

func (r *ETCD) ReadBytes() ([]byte, error)

ReadBytes reads the contents of a key from etcd and returns the bytes.

func (*ETCD) Watch

func (r *ETCD) Watch(ctx context.Context, reload func() error) error

Watch watches the change to the remote key from etcd. If the key is edited or created, the reload function will be called. note the reload function should not just load the changes made within this key, but rather it should reload the whole config stack. For example, if the flag or env takes precedence over the config key, they should remain to be so after the key changes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL