当前位置: 首页>>代码示例>>Golang>>正文


Golang viper.New函数代码示例

本文整理汇总了Golang中github.com/spf13/viper.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: setDefaultConfigValuesWithViper

func setDefaultConfigValuesWithViper(v *viper.Viper, b *BgpConfigSet) error {
	if v == nil {
		v = viper.New()
	}

	if err := SetDefaultGlobalConfigValues(&b.Global); err != nil {
		return err
	}

	for idx, server := range b.BmpServers {
		if server.Config.Port == 0 {
			server.Config.Port = bmp.BMP_DEFAULT_PORT
		}
		b.BmpServers[idx] = server
	}

	if b.Zebra.Config.Url == "" {
		b.Zebra.Config.Url = "unix:/var/run/quagga/zserv.api"
	}

	list, err := extractArray(v.Get("neighbors"))
	if err != nil {
		return err
	}

	for idx, n := range b.Neighbors {
		vv := viper.New()
		if len(list) > idx {
			vv.Set("neighbor", list[idx])
		}
		if err := setDefaultNeighborConfigValuesWithViper(vv, &n, b.Global.Config.As); err != nil {
			return err
		}
		b.Neighbors[idx] = n
	}

	for idx, r := range b.RpkiServers {
		if r.Config.Port == 0 {
			b.RpkiServers[idx].Config.Port = rtr.RPKI_DEFAULT_PORT
		}
	}

	list, err = extractArray(v.Get("policy-definitions"))
	if err != nil {
		return err
	}

	for idx, p := range b.PolicyDefinitions {
		vv := viper.New()
		if len(list) > idx {
			vv.Set("policy", list[idx])
		}
		if err := setDefaultPolicyConfigValuesWithViper(vv, &p); err != nil {
			return err
		}
		b.PolicyDefinitions[idx] = p
	}

	return nil
}
开发者ID:rafaelsilvag,项目名称:gobgp,代码行数:60,代码来源:default.go

示例2: TestGetTrustPinningErrors

func TestGetTrustPinningErrors(t *testing.T) {
	setUp(t)
	invalidTrustPinConfig := tempDirWithConfig(t, `{
		"trust_pinning": {
		    "certs": {
		        "repo3": [60, "abc", [1, 2, 3]]
		    }
		 }
	}`)
	defer os.RemoveAll(invalidTrustPinConfig)

	tc := &tufCommander{
		// returns a nil pointer
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetConfigFile(filepath.Join(invalidTrustPinConfig, "config.json"))
			v.ReadInConfig()
			return v, nil
		},
	}
	require.Error(t, tc.tufStatus(&cobra.Command{}, []string{"gun"}))
	tc.resetAll = true
	require.Error(t, tc.tufReset(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufDeleteGUN(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufInit(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufPublish(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufVerify(&cobra.Command{}, []string{"gun", "target", "file"}))
	require.Error(t, tc.tufLookup(&cobra.Command{}, []string{"gun", "target"}))
	require.Error(t, tc.tufList(&cobra.Command{}, []string{"gun"}))
	require.Error(t, tc.tufAdd(&cobra.Command{}, []string{"gun", "target", "file"}))
	require.Error(t, tc.tufRemove(&cobra.Command{}, []string{"gun", "target", "file"}))
	require.Error(t, tc.tufWitness(&cobra.Command{}, []string{"gun", "targets/role"}))
	tc.sha256 = "88b76b34ab83a9e4d5abe3697950fb73f940aab1aa5b534f80cf9de9708942be"
	require.Error(t, tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test1", "100"}))
}
开发者ID:jfrazelle,项目名称:notary,代码行数:35,代码来源:tuf_test.go

示例3: TestStatusUnstageAndReset

func TestStatusUnstageAndReset(t *testing.T) {
	setUp(t)
	tempBaseDir := tempDirWithConfig(t, "{}")
	defer os.RemoveAll(tempBaseDir)

	tc := &tufCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}

	// run a reset with an empty changelist and make sure it succeeds
	tc.resetAll = true
	err := tc.tufReset(&cobra.Command{}, []string{"gun"})
	require.NoError(t, err)

	// add some targets
	tc.sha256 = "88b76b34ab83a9e4d5abe3697950fb73f940aab1aa5b534f80cf9de9708942be"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test1", "100"})
	require.NoError(t, err)
	tc.sha256 = "4a7c203ce63b036a1999ea74eebd307c338368eb2b32218b722de6c5fdc7f016"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test2", "100"})
	require.NoError(t, err)
	tc.sha256 = "64bd0565907a6a55fc66fd828a71dbadd976fa875d0a3869f53d02eb8710ecb4"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test3", "100"})
	require.NoError(t, err)
	tc.sha256 = "9d9e890af64dd0f44b8a1538ff5fa0511cc31bf1ab89f3a3522a9a581a70fad8"
	err = tc.tufAddByHash(&cobra.Command{}, []string{"gun", "test4", "100"})
	require.NoError(t, err)

	out, err := runCommand(t, tempBaseDir, "status", "gun")
	require.NoError(t, err)
	require.Contains(t, out, "test1")
	require.Contains(t, out, "test2")
	require.Contains(t, out, "test3")
	require.Contains(t, out, "test4")

	_, err = runCommand(t, tempBaseDir, "reset", "gun", "-n", "-1,1,3,10")
	require.NoError(t, err)

	out, err = runCommand(t, tempBaseDir, "status", "gun")
	require.NoError(t, err)
	require.Contains(t, out, "test1")
	require.NotContains(t, out, "test2")
	require.Contains(t, out, "test3")
	require.NotContains(t, out, "test4")

	_, err = runCommand(t, tempBaseDir, "reset", "gun", "--all")
	require.NoError(t, err)

	out, err = runCommand(t, tempBaseDir, "status", "gun")
	require.NoError(t, err)
	require.NotContains(t, out, "test1")
	require.NotContains(t, out, "test2")
	require.NotContains(t, out, "test3")
	require.NotContains(t, out, "test4")

}
开发者ID:jfrazelle,项目名称:notary,代码行数:60,代码来源:tuf_test.go

示例4: init

func init() {
	c := viper.New()

	c.SetEnvPrefix("Q")
	c.AutomaticEnv()

	flag.StringVar(&configFile, "config", "", "")
	flag.Parse()
	c.BindPFlag("config", flag.Lookup("config"))

	if c.GetString("config") == "" {
		// Read from "default" configuration path
		c.SetConfigName("config")
		c.AddConfigPath("/etc/qurid")
		c.AddConfigPath("$HOME/.quarid")
		c.AddConfigPath(".")
	} else {
		c.SetConfigFile(c.GetString("config"))
	}

	if err := c.ReadInConfig(); err != nil {
		panic(fmt.Errorf("Unable to read any configuration file: %s\n", err))
	}

	location, err := time.LoadLocation(c.GetString("timezone"))
	if err == nil {
		c.Set("timezone", location)
	} else {
		c.Set("timezone", time.UTC)
	}

	config = c
}
开发者ID:LiranCohen,项目名称:quarid-go,代码行数:33,代码来源:config.go

示例5: TestExportKeysByID

func TestExportKeysByID(t *testing.T) {
	setUp(t)
	tempBaseDir, err := ioutil.TempDir("", "notary-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tempBaseDir)
	output, err := ioutil.TempFile("", "notary-test-import-")
	require.NoError(t, err)
	defer os.RemoveAll(output.Name())
	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			return v, nil
		},
	}
	k.outFile = output.Name()
	err = output.Close() // close so export can open
	require.NoError(t, err)
	k.exportKeyIDs = []string{"one", "three"}

	b := &pem.Block{}
	b.Bytes = make([]byte, 1000)
	rand.Read(b.Bytes)

	b2 := &pem.Block{}
	b2.Bytes = make([]byte, 1000)
	rand.Read(b2.Bytes)

	c := &pem.Block{}
	c.Bytes = make([]byte, 1000)
	rand.Read(c.Bytes)

	bBytes := pem.EncodeToMemory(b)
	b2Bytes := pem.EncodeToMemory(b2)
	cBytes := pem.EncodeToMemory(c)

	fileStore, err := store.NewPrivateKeyFileStorage(tempBaseDir, notary.KeyExtension)
	require.NoError(t, err)
	err = fileStore.Set("one", bBytes)
	require.NoError(t, err)
	err = fileStore.Set("two", b2Bytes)
	require.NoError(t, err)
	err = fileStore.Set("three", cBytes)
	require.NoError(t, err)

	err = k.exportKeys(&cobra.Command{}, nil)
	require.NoError(t, err)

	outRes, err := ioutil.ReadFile(k.outFile)
	require.NoError(t, err)

	block, rest := pem.Decode(outRes)
	require.Equal(t, b.Bytes, block.Bytes)
	require.Equal(t, "one", block.Headers["path"])

	block, rest = pem.Decode(rest)
	require.Equal(t, c.Bytes, block.Bytes)
	require.Equal(t, "three", block.Headers["path"])
	require.Len(t, rest, 0)
}
开发者ID:jfrazelle,项目名称:notary,代码行数:60,代码来源:keys_test.go

示例6: GetConfig

func GetConfig() *viper.Viper {

	env := os.Getenv("VIPER_ENV")

	if len(env) == 0 {
		env = "development"
	}

	config := viper.New()

	config.SetConfigName(env) // name of config file (without extension)

	configPath := os.Getenv("VIPER_CONFIG")

	if len(configPath) == 0 {
		configPath = "config"
	}

	config.AddConfigPath(configPath)

	err := config.ReadInConfig() // Find and read the config file
	if err != nil {              // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s]: %s \n", configPath, err))
	}

	return config
}
开发者ID:r0b6,项目名称:gin-microservice,代码行数:27,代码来源:config.go

示例7: init

func init() {
	cfg = viper.New()
	cfg.SetDefault("agent.analyzers", "127.0.0.1:8082")
	cfg.SetDefault("agent.listen", "127.0.0.1:8081")
	cfg.SetDefault("agent.flowtable_expire", 300)
	cfg.SetDefault("agent.flowtable_update", 30)
	cfg.SetDefault("ovs.ovsdb", "127.0.0.1:6400")
	cfg.SetDefault("graph.backend", "memory")
	cfg.SetDefault("graph.gremlin", "ws://127.0.0.1:8182")
	cfg.SetDefault("sflow.bind_address", "127.0.0.1:6345")
	cfg.SetDefault("sflow.port_min", 6345)
	cfg.SetDefault("sflow.port_max", 6355)
	cfg.SetDefault("analyzer.listen", "127.0.0.1:8082")
	cfg.SetDefault("analyzer.flowtable_expire", 600)
	cfg.SetDefault("analyzer.flowtable_update", 60)
	cfg.SetDefault("storage.elasticsearch", "127.0.0.1:9200")
	cfg.SetDefault("ws_pong_timeout", 5)
	cfg.SetDefault("docker.url", "unix:///var/run/docker.sock")
	cfg.SetDefault("etcd.data_dir", "/tmp/skydive-etcd")
	cfg.SetDefault("etcd.embedded", true)
	cfg.SetDefault("etcd.port", 2379)
	cfg.SetDefault("etcd.servers", []string{"http://127.0.0.1:2379"})
	cfg.SetDefault("auth.type", "noauth")
	cfg.SetDefault("auth.keystone.tenant", "admin")
}
开发者ID:lebauce,项目名称:skydive,代码行数:25,代码来源:config.go

示例8: AddSettings

func (env *Env) AddSettings(frontmatter string) (*Env, error) {
	v := viper.New()
	v.SetConfigType("yaml")
	err := v.ReadConfig(bytes.NewBufferString(frontmatter))
	env.AddPairs(v.AllSettings())
	return env, err
}
开发者ID:MondayHopscotch,项目名称:genfront,代码行数:7,代码来源:env.go

示例9: Build

func Build() (err error) {

	err = AppSettings.UnmarshalKey(AppSettings.GetString("env"), Config)
	if err != nil {
		return
	}

	Config.Address = AppSettings.GetString("address")
	Config.Port = AppSettings.GetString("port")

	s3Config := &S3Config{}
	err = S3Settings.UnmarshalKey(S3Settings.GetString("env"), s3Config)
	if err != nil {
		return
	}
	Config.S3Config = s3Config

	sizes := viper.New()
	sizes.SetConfigName("sizes")
	sizes.AddConfigPath("./")

	err = sizes.ReadInConfig()
	if err != nil {
		return
	}

	mapSizes := &ValidSizes{}
	err = sizes.UnmarshalKey(AppSettings.GetString("env"), mapSizes)
	if err != nil {
		return
	}
	Config.ValidSizes = mapSizes

	return
}
开发者ID:Arimeka,项目名称:static-proxy,代码行数:35,代码来源:settings.go

示例10: TestRotateKeyInvalidRoles

// Non-roles and delegation keys can't be rotated with the command line
func TestRotateKeyInvalidRoles(t *testing.T) {
	setUp(t)
	invalids := []string{
		"notevenARole",
		"targets/a",
	}
	for _, role := range invalids {
		for _, serverManaged := range []bool{true, false} {
			k := &keyCommander{
				configGetter:           func() (*viper.Viper, error) { return viper.New(), nil },
				getRetriever:           func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
				rotateKeyRole:          role,
				rotateKeyServerManaged: serverManaged,
			}
			commands := []string{"gun", role}
			if serverManaged {
				commands = append(commands, "-r")
			}
			err := k.keysRotate(&cobra.Command{}, commands)
			require.Error(t, err)
			require.Contains(t, err.Error(),
				fmt.Sprintf("does not currently permit rotating the %s key", role))
		}
	}
}
开发者ID:cyli,项目名称:notary,代码行数:26,代码来源:keys_test.go

示例11: loadConfig

func loadConfig() (config *viper.Viper) {
	config = viper.New()

	// for environment variables
	config.SetEnvPrefix(configPrefix)
	config.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	config.SetEnvKeyReplacer(replacer)

	config.SetConfigName("config")
	config.AddConfigPath("./")
	config.AddConfigPath("../consensus/obcpbft/")
	config.AddConfigPath("../../consensus/obcpbft")
	// Path to look for the config file in based on GOPATH
	gopath := os.Getenv("GOPATH")
	for _, p := range filepath.SplitList(gopath) {
		obcpbftpath := filepath.Join(p, "src/github.com/hyperledger/fabric/consensus/obcpbft")
		config.AddConfigPath(obcpbftpath)
	}

	err := config.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Error reading %s plugin config: %s", configPrefix, err))
	}
	return
}
开发者ID:magooster,项目名称:obc-peer,代码行数:26,代码来源:obc-pbft.go

示例12: GetReplicaHash

// GetReplicaHash returns the crypto IDs of the current replica and the whole network
// TODO func (h *Helper) GetReplicaHash() (self []byte, network [][]byte, err error) {
// ATTN: Until the crypto package is integrated, this functions returns
// the <IP:port>s of the current replica and the whole network instead
func (h *Helper) GetReplicaHash() (self string, network []string, err error) {
	// v, _ := h.coordinator.GetValidator()
	// self = v.GetID()
	peer, err := peer.GetPeerEndpoint()
	if err != nil {
		return "", nil, err
	}
	self = peer.Address

	config := viper.New()
	config.SetConfigName("openchain")
	config.AddConfigPath("./")
	err = config.ReadInConfig()
	if err != nil {
		err = fmt.Errorf("Fatal error reading root config: %s", err)
		return self, nil, err
	}

	// encodedHashes := config.GetStringSlice("peer.validator.replicas.hashes")
	/* network = make([][]byte, len(encodedHashes))
	for i, v := range encodedHashes {
		network[i], _ = base64.StdEncoding.DecodeString(v)
	} */
	network = config.GetStringSlice("peer.validator.replicas.ips")

	return self, network, nil
}
开发者ID:masterDev1985,项目名称:obc-peer,代码行数:31,代码来源:helper.go

示例13: TestRotateKeyRemoteServerManagesKey

// The command line uses NotaryRepository's RotateKey - this is just testing
// that the correct config variables are passed for the client to request a key
// from the remote server.
func TestRotateKeyRemoteServerManagesKey(t *testing.T) {
	// Temporary directory where test files will be created
	tempBaseDir, err := ioutil.TempDir("/tmp", "notary-test-")
	defer os.RemoveAll(tempBaseDir)
	assert.NoError(t, err, "failed to create a temporary directory: %s", err)
	gun := "docker.com/notary"

	ret := passphrase.ConstantRetriever("pass")

	ts, initialKeys := setUpRepo(t, tempBaseDir, gun, ret)
	defer ts.Close()

	k := &keyCommander{
		configGetter: func() (*viper.Viper, error) {
			v := viper.New()
			v.SetDefault("trust_dir", tempBaseDir)
			v.SetDefault("remote_server.url", ts.URL)
			return v, nil
		},
		getRetriever:           func() passphrase.Retriever { return ret },
		rotateKeyRole:          data.CanonicalSnapshotRole,
		rotateKeyServerManaged: true,
	}
	err = k.keysRotate(&cobra.Command{}, []string{gun})
	assert.NoError(t, err)

	repo, err := client.NewNotaryRepository(tempBaseDir, gun, ts.URL, nil, ret)
	assert.NoError(t, err, "error creating repo: %s", err)

	cl, err := repo.GetChangelist()
	assert.NoError(t, err, "unable to get changelist: %v", err)
	assert.Len(t, cl.List(), 1)
	// no keys have been created, since a remote key was specified
	assert.Equal(t, initialKeys, repo.CryptoService.ListAllKeys())
}
开发者ID:carriercomm,项目名称:notary,代码行数:38,代码来源:keys_test.go

示例14: configure

// initializes a viper object with test configuration
func configure(jsonConfig string) *viper.Viper {
	config := viper.New()
	SetupViper(config, envPrefix)
	config.SetConfigType("json")
	config.ReadConfig(bytes.NewBuffer([]byte(jsonConfig)))
	return config
}
开发者ID:mbentley,项目名称:notary,代码行数:8,代码来源:configuration_test.go

示例15: TestEnvSlice

func TestEnvSlice(t *testing.T) {
	envVar := "ORDERER_INNER_SLICE"
	envVal := "[a, b, c]"
	os.Setenv(envVar, envVal)
	defer os.Unsetenv(envVar)
	config := viper.New()
	config.SetEnvPrefix(Prefix)
	config.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	config.SetEnvKeyReplacer(replacer)
	config.SetConfigType("yaml")

	data := "---\nInner:\n    Slice: [d,e,f]"

	err := config.ReadConfig(bytes.NewReader([]byte(data)))

	if err != nil {
		t.Fatalf("Error reading %s plugin config: %s", Prefix, err)
	}

	var uconf testSlice

	err = ExactWithDateUnmarshal(config, &uconf)
	if err != nil {
		t.Fatalf("Failed to unmarshal with: %s", err)
	}

	expected := []string{"a", "b", "c"}
	if !reflect.DeepEqual(uconf.Inner.Slice, expected) {
		t.Fatalf("Did not get back the right slice, expeced: %v got %v", expected, uconf.Inner.Slice)
	}
}
开发者ID:hyperledger,项目名称:fabric,代码行数:32,代码来源:config_test.go


注:本文中的github.com/spf13/viper.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。