替换viper地图中的键而不替换整个地图。

huangapple go评论90阅读模式
英文:

Replace viper map key without replacing entire map

问题

我正在使用viper进行配置。如何在不替换整个映射的情况下替换一个键?

package main

import (
	"log"

	"github.com/spf13/viper"
)

type person struct {
	First string
	Last  string
}

func main() {
	v := viper.New()
	v.SetEnvPrefix("mememe")
	v.AutomaticEnv()

	bob := person{
		First: "Bob",
		Last:  "Smith",
	}

	john := person{
		First: "John",
		Last:  "Boothe",
	}

	v.SetDefault("people.bob", bob)
	v.SetDefault("people.john", john)
	log.Println(v.Get("people")) // map[bob:{Bob Smith} john:{John Boothe}]

	bob.Last = "Hope"
	v.Set("people.bob", bob)
	log.Println(v.Get("people")) // map[bob:{Bob Hope}]
}

在设置新的Bob时,我完全丢失了John。如果我将"SetDefault"更改为简单的"Set",似乎可以工作,但我想知道为什么"SetDefault"不起作用。

英文:

I am using viper for my config. How do I replace a key without replacing the entire map?

package main

import (
	"log"

	"github.com/spf13/viper"
)

type person struct {
	First string
	Last  string
}

func main() {
	v := viper.New()
	v.SetEnvPrefix("mememe")
	v.AutomaticEnv()

	bob := person{
		First: "Bob",
		Last:  "Smith",
	}

	john := person{
		First: "John",
		Last:  "Boothe",
	}

	v.SetDefault("people.bob", bob)
	v.SetDefault("people.john", john)
	log.Println(v.Get("people")) // map[bob:{Bob Smith} john:{John Boothe}]

	bob.Last = "Hope"
	v.Set("people.bob", bob)
	log.Println(v.Get("people")) // map[bob:{Bob Hope}]

}

Upon setting the new Bob I lose John completely. If I change "SetDefault" to simply "Set" then it seems to work but I am wondering why "SetDefault" doesn't work.

答案1

得分: 0

我猜是因为这个原因,来自于访问嵌套键的文档。

然而,如果datastore.metric被一个立即值(通过标志、环境变量、Set()方法等)覆盖,那么datastore.metric的所有子键将变为未定义,它们被更高优先级的配置级别“遮蔽”。

所以一旦设置了people.bobpeople就会存在,并且people.*不再被视为未填充。

我不知道如何解决这个问题。

英文:

I'm going to guess it's because of this, from the docs on Accessing nested keys.

> However, if datastore.metric was overridden (by a flag, an environment variable, the Set() method, …) with an immediate value, then all sub-keys of datastore.metric become undefined, they are “shadowed” by the higher-priority configuration level.

So as soon as people.bob is set, people springs into existence and people.* are no longer considered unpopulated.

I don't know how to work around it.

huangapple
  • 本文由 发表于 2017年5月30日 01:17:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/44247616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定