config consul source supports slash as prefix

`config.NewConfig()` with consul source will both read from consul
and watch consul for changes. Hence, the `prefix` is used in these
2 cases:

- read case: it is used to strip path based on the `KVPair` returned
from consul `kv.List()` method
- watch case: it is used as the `key` of watch query (`keyprefix` type)

So for *watch case*, the `key` is leagal to be `/` for watching change
on root. While for *read case*, because `KVPair.Key` is always stripped
off the leading slash, so if user specified some `prefix` with leading
slash, we should strip it also.

An extream case would be: user want's to read & watch node in root dir.
One would specify `prefix` as `/`, and it should work then.
This commit is contained in:
magodo 2019-06-21 16:35:48 +08:00
parent 1765be049b
commit 7acd249147
3 changed files with 5 additions and 5 deletions

View File

@ -4,7 +4,7 @@ The consul source reads config from consul key/values
## Consul Format
The consul source expects keys under the default prefix `micro/config`
The consul source expects keys under the default prefix `/micro/config`
Values are expected to be json
@ -29,8 +29,8 @@ Specify source with data
consulSource := consul.NewSource(
// optionally specify consul address; default to localhost:8500
consul.WithAddress("10.0.0.10:8500"),
// optionally specify prefix; defaults to micro/config
consul.WithPrefix("my/prefix"),
// optionally specify prefix; defaults to /micro/config
consul.WithPrefix("/my/prefix"),
// optionally strip the provided prefix from the keys, defaults to false
consul.StripPrefix(true),
)

View File

@ -21,7 +21,7 @@ type consul struct {
var (
// DefaultPrefix is the prefix that consul keys will be assumed to have if you
// haven't specified one
DefaultPrefix = "micro/config/"
DefaultPrefix = "/micro/config/"
)
func (c *consul) Read() (*source.ChangeSet, error) {

View File

@ -13,7 +13,7 @@ func makeMap(e encoder.Encoder, kv api.KVPairs, stripPrefix string) (map[string]
// consul guarantees lexicographic order, so no need to sort
for _, v := range kv {
pathString := strings.TrimPrefix(strings.TrimPrefix(v.Key, stripPrefix), "/")
pathString := strings.TrimPrefix(strings.TrimPrefix(v.Key, strings.TrimPrefix(stripPrefix, "/")), "/")
var val map[string]interface{}
// ensure a valid value is stored at this location