• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang viper.Set函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: SetupSuite

func (suite *HelpCommandTestSuite) SetupSuite() {
	DJ = bot.NewMumbleDJ()

	viper.Set("commands.help.aliases", []string{"help", "h"})
	viper.Set("commands.help.description", "help")
	viper.Set("commands.help.is_admin", false)
}
开发者ID:matthieugrieger,项目名称:mumbledj,代码行数:7,代码来源:help_test.go


示例2: SetupSuite

func (suite *CacheSizeCommandTestSuite) SetupSuite() {
	DJ = bot.NewMumbleDJ()

	viper.Set("commands.cachesize.aliases", []string{"cachesize", "cs"})
	viper.Set("commands.cachesize.description", "cachesize")
	viper.Set("commands.cachesize.is_admin", true)
}
开发者ID:matthieugrieger,项目名称:mumbledj,代码行数:7,代码来源:cachesize_test.go


示例3: server

func server(cmd *cobra.Command, args []string) {
	InitializeConfig()

	if cmd.Flags().Lookup("disableLiveReload").Changed {
		viper.Set("DisableLiveReload", disableLiveReload)
	}

	if serverWatch {
		viper.Set("Watch", true)
	}

	if viper.GetBool("watch") {
		serverWatch = true
	}

	l, err := net.Listen("tcp", net.JoinHostPort(serverInterface, strconv.Itoa(serverPort)))
	if err == nil {
		l.Close()
	} else {
		jww.ERROR.Println("port", serverPort, "already in use, attempting to use an available port")
		sp, err := helpers.FindAvailablePort()
		if err != nil {
			jww.ERROR.Println("Unable to find alternative port to use")
			jww.ERROR.Fatalln(err)
		}
		serverPort = sp.Port
	}

	viper.Set("port", serverPort)

	BaseURL, err := fixURL(BaseURL)
	if err != nil {
		jww.ERROR.Fatal(err)
	}
	viper.Set("BaseURL", BaseURL)

	if err := memStats(); err != nil {
		jww.ERROR.Println("memstats error:", err)
	}

	build(serverWatch)

	// Watch runs its own server as part of the routine
	if serverWatch {
		watched := getDirList()
		workingDir := helpers.AbsPathify(viper.GetString("WorkingDir"))
		for i, dir := range watched {
			watched[i], _ = helpers.GetRelativePath(dir, workingDir)
		}
		unique := strings.Join(helpers.RemoveSubpaths(watched), ",")

		jww.FEEDBACK.Printf("Watching for changes in %s/{%s}\n", workingDir, unique)
		err := NewWatcher(serverPort)
		if err != nil {
			fmt.Println(err)
		}
	}

	serve(serverPort)
}
开发者ID:heidthecamp,项目名称:hugo,代码行数:60,代码来源:server.go


示例4: initConfig

// initConfig reads in config file and ENV variables if set.
func initConfig(cmd *cobra.Command) {
	viper.SetConfigName(".skelly") // name of config file (without extension)
	viper.AddConfigPath("$HOME")   // adding home directory as first search path
	viper.SetConfigType("json")
	viper.AutomaticEnv() // read in environment variables that match

	fmt.Println("got here")
	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	// Make sure that go src var is set
	gopath = viper.GetString("gopath")
	if len(gopath) <= 0 {
		gopath = joinPath(os.Getenv("GOPATH"), "src")
		viper.Set("gopath", gopath)
	}

	if cmd.Flags().Lookup("project-root").Changed {
		viper.Set("project-root", basePath)
	}
	if cmd.Flags().Lookup("author").Changed {
		fmt.Println("adding author")
		viper.Set("author", author)
	}
	if cmd.Flags().Lookup("email").Changed {
		viper.Set("email", email)
	}
	fmt.Println(email)
	if cmd.Flags().Lookup("license").Changed {
		viper.Set("license", license)
	}
}
开发者ID:lursu,项目名称:skelly,代码行数:35,代码来源:root.go


示例5: TestPageCount

func TestPageCount(t *testing.T) {
	testCommonResetState()
	hugofs.InitMemFs()

	viper.Set("uglyURLs", false)
	viper.Set("paginate", 10)
	s := &Site{
		Source:   &source.InMemorySource{ByteSource: urlFakeSource},
		Language: helpers.NewDefaultLanguage(),
	}

	if err := buildAndRenderSite(s, "indexes/blue.html", indexTemplate); err != nil {
		t.Fatalf("Failed to build site: %s", err)
	}
	_, err := hugofs.Destination().Open("public/blue")
	if err != nil {
		t.Errorf("No indexed rendered.")
	}

	for _, s := range []string{
		"public/sd1/foo/index.html",
		"public/sd2/index.html",
		"public/sd3/index.html",
		"public/sd4.html",
	} {
		if _, err := hugofs.Destination().Open(filepath.FromSlash(s)); err != nil {
			t.Errorf("No alias rendered: %s", s)
		}
	}
}
开发者ID:digitalcraftsman,项目名称:hugo,代码行数:30,代码来源:site_url_test.go


示例6: setRomanaRootURL

// setRomanaRootURL sanitizes rootURL and rootPort and also
// sets baseURL which is needed to connect to other romana
// services.
func setRomanaRootURL() {
	// Variables used for configuration and flags.
	var baseURL string
	var rootURL string
	var rootPort string

	// Add port details to rootURL else try localhost
	// if nothing is given on command line or config.
	rootURL = config.GetString("RootURL")
	rootPort = config.GetString("RootPort")
	if rootPort == "" {
		re, _ := regexp.Compile(`:\d+/?`)
		port := re.FindString(rootURL)
		port = strings.TrimPrefix(port, ":")
		port = strings.TrimSuffix(port, "/")
		if port != "" {
			rootPort = port
		} else {
			rootPort = "9600"
		}
	}
	config.Set("RootPort", rootPort)
	if rootURL != "" {
		baseURL = strings.TrimSuffix(rootURL, "/")
		baseURL = strings.TrimSuffix(baseURL, ":9600")
		baseURL = strings.TrimSuffix(baseURL, ":"+rootPort)
	} else {
		baseURL = "http://localhost"
	}
	config.Set("BaseURL", baseURL)
	rootURL = baseURL + ":" + rootPort + "/"
	config.Set("RootURL", rootURL)
}
开发者ID:romana,项目名称:core,代码行数:36,代码来源:main.go


示例7: TestRelURL

func TestRelURL(t *testing.T) {
	defer viper.Reset()
	//defer viper.Set("canonifyURLs", viper.GetBool("canonifyURLs"))
	tests := []struct {
		input    string
		baseURL  string
		canonify bool
		expected string
	}{
		{"/test/foo", "http://base/", false, "/test/foo"},
		{"test.css", "http://base/sub", false, "/sub/test.css"},
		{"test.css", "http://base/sub", true, "/test.css"},
		{"/test/", "http://base/", false, "/test/"},
		{"/test/", "http://base/sub/", false, "/sub/test/"},
		{"/test/", "http://base/sub/", true, "/test/"},
		{"", "http://base/ace/", false, "/ace/"},
		{"", "http://base/ace", false, "/ace"},
		{"http://abs", "http://base/", false, "http://abs"},
		{"//schemaless", "http://base/", false, "//schemaless"},
	}

	for i, test := range tests {
		viper.Reset()
		viper.Set("BaseURL", test.baseURL)
		viper.Set("canonifyURLs", test.canonify)

		output := RelURL(test.input)
		if output != test.expected {
			t.Errorf("[%d][%t] Expected %#v, got %#v\n", i, test.canonify, test.expected, output)
		}
	}
}
开发者ID:CODECOMMUNITY,项目名称:hugo,代码行数:32,代码来源:url_test.go


示例8: TestReadPagesFromSourceWithEmptySource

// Issue #1797
func TestReadPagesFromSourceWithEmptySource(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	viper.Set("DefaultExtension", "html")
	viper.Set("verbose", true)
	viper.Set("baseurl", "http://auth/bub")

	sources := []source.ByteSource{}

	s := &Site{
		Source:  &source.InMemorySource{ByteSource: sources},
		targets: targetList{page: &target.PagePub{UglyURLs: true}},
	}

	var err error
	d := time.Second * 2
	ticker := time.NewTicker(d)
	select {
	case err = <-s.ReadPagesFromSource():
		break
	case <-ticker.C:
		err = fmt.Errorf("ReadPagesFromSource() never returns in %s", d.String())
	}
	ticker.Stop()
	if err != nil {
		t.Fatalf("Unable to read source: %s", err)
	}
}
开发者ID:nitoyon,项目名称:hugo,代码行数:30,代码来源:site_test.go


示例9: SetupSuite

func (suite *ToggleShuffleCommandTestSuite) SetupSuite() {
	DJ = bot.NewMumbleDJ()

	viper.Set("commands.toggleshuffle.aliases", []string{"toggleshuffle", "ts"})
	viper.Set("commands.toggleshuffle.description", "toggleshuffle")
	viper.Set("commands.toggleshuffle.is_admin", true)
}
开发者ID:matthieugrieger,项目名称:mumbledj,代码行数:7,代码来源:toggleshuffle_test.go


示例10: cmdSetup

func cmdSetup(c *cli.Context) {
	token := c.Args().First()

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := qiita.NewClient(tc)
	user, err := client.AuthenticatedUser.Show()
	if err != nil {
		fmt.Println("Auth failed")
		os.Exit(1)
	}

	loadConfig()
	viper.Set("accessToken", token)
	viper.Set("id", user.Id)

	err = saveConfig()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println("Token saved")
}
开发者ID:uetchy,项目名称:alfred-qiita-workflow,代码行数:26,代码来源:setup.go


示例11: TestRobotsTXTOutput

func TestRobotsTXTOutput(t *testing.T) {
	testCommonResetState()

	hugofs.InitMemFs()

	viper.Set("baseurl", "http://auth/bub/")
	viper.Set("enableRobotsTXT", true)

	s := &Site{
		Source:   &source.InMemorySource{ByteSource: weightedSources},
		Language: helpers.NewDefaultLanguage(),
	}

	if err := buildAndRenderSite(s, "robots.txt", robotTxtTemplate); err != nil {
		t.Fatalf("Failed to build site: %s", err)
	}

	robotsFile, err := hugofs.Destination().Open("public/robots.txt")

	if err != nil {
		t.Fatalf("Unable to locate: robots.txt")
	}

	robots := helpers.ReaderToBytes(robotsFile)
	if !bytes.HasPrefix(robots, []byte("User-agent: Googlebot")) {
		t.Errorf("Robots file should start with 'User-agentL Googlebot'. %s", robots)
	}
}
开发者ID:tarsisazevedo,项目名称:hugo,代码行数:28,代码来源:robotstxt_test.go


示例12: InitializeConfig

// InitializeConfig initializes a config file with sensible default configuration flags.
func InitializeConfig() {
	viper.SetConfigName("grasshopper")          // name of config file (without extension)
	viper.AddConfigPath("/etc/grasshopper.d/")  // path to look for the config file
	viper.AddConfigPath("$HOME/.grasshopper.d") // call multiple times to add many search paths
	viper.AddConfigPath(".")                    // optionally look for config in the working directory

	// read config from storage
	err := viper.ReadInConfig() // FIXME
	if err != nil {
		jww.INFO.Println("Unable to locate Config file. I will fall back to my defaults...")
	}

	// default settings
	viper.SetDefault("Verbose", false)
	viper.SetDefault("DryRun", false)
	viper.SetDefault("DoLog", true)

	// bind config to command flags
	if grasshopperCmdV.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}
	if grasshopperCmdV.PersistentFlags().Lookup("log").Changed {
		viper.Set("DoLog", DoLog)
	}
}
开发者ID:vpavlin,项目名称:grasshopper,代码行数:26,代码来源:grasshopper.go


示例13: main

func main() {
	viper.Set("version", version)
	viper.Set("gitBranch", gitBranch)
	viper.Set("gitCommit", gitCommit)
	viper.Set("buildDate", buildDate)
	cmd.Execute()
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:7,代码来源:main.go


示例14: msgBuffer

func msgBuffer() {
	params := &sqs.ReceiveMessageInput{
		QueueUrl: aws.String(viper.GetString("URL") + ID),
		AttributeNames: []*string{
			aws.String("All"),
		},
		MaxNumberOfMessages: aws.Int64(10),
		MessageAttributeNames: []*string{
			aws.String("Dest." + ID),
		},
		VisibilityTimeout: aws.Int64(1),
	}

	resp, err := svc.ReceiveMessage(params)
	errHandle(err)
	for _, element := range resp.Messages {
		var m Message
		data, _ := strconv.Unquote(awsutil.Prettify(element.Body))
		b := []byte(data)
		err := json.Unmarshal(b, &m)
		errHandle(err)
		//This is where we will send the message to the queue for the service
		viper.Set("Dest", m.Dest)
		viper.Set("Sender", m.Sender)
		go execute(m)
		//If all goes well, the message has been forwarded to the responsible queue
		deleteMsg(element)
	}
}
开发者ID:SeleneSoftware,项目名称:Hermes,代码行数:29,代码来源:main.go


示例15: InitializeCertAuthConfig

// InitializeCertAuthConfig sets up the command line options for creating a CA
func InitializeCertAuthConfig(logger log.Logger) error {

	viper.SetDefault("Bits", "4096")
	viper.SetDefault("Years", "10")
	viper.SetDefault("Organization", "kappa-ca")
	viper.SetDefault("Country", "USA")

	if initCmd.PersistentFlags().Lookup("bits").Changed {
		logger.Info("", "Bits", KeyBits)
		viper.Set("Bits", KeyBits)
	}
	if initCmd.PersistentFlags().Lookup("years").Changed {
		logger.Info("", "Years", Years)
		viper.Set("Years", Years)
	}
	if initCmd.PersistentFlags().Lookup("organization").Changed {
		logger.Info("", "Organization", Organization)
		viper.Set("Organization", Organization)
	}
	if initCmd.PersistentFlags().Lookup("country").Changed {
		logger.Info("", "Country", Country)
		viper.Set("Country", Country)
	}
	if initCmd.PersistentFlags().Lookup("hosts").Changed {
		logger.Info("", "Hosts", Hosts)
		viper.Set("Hosts", Hosts)
	}

	return nil
}
开发者ID:blacklabeldata,项目名称:kappa,代码行数:31,代码来源:init-ca.go


示例16: initConfig

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".gogetgithubstats") // name of config file (without extension)
	viper.AddConfigPath("$HOME")             // adding home directory as first search path
	viper.AutomaticEnv()                     // read in environment variables that match

	// This is the defaults
	viper.SetDefault("Verbose", true)

	// If a config file is found, read it in.
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			jww.ERROR.Println(err)
		} else {
			jww.ERROR.Println("Unable to locate Config file.", err)
		}
	}

	if rootCmdV.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}

	if rootCmdV.PersistentFlags().Lookup("access-token").Changed {
		viper.Set("access-token", accessToken)
	}

	if viper.GetBool("verbose") {
		jww.SetStdoutThreshold(jww.LevelDebug)
	}
}
开发者ID:goern,项目名称:gogetgithubstats,代码行数:35,代码来源:root.go


示例17: TestDefaultHandler

func TestDefaultHandler(t *testing.T) {
	testCommonResetState()

	hugofs.InitMemFs()
	sources := []source.ByteSource{
		{Name: filepath.FromSlash("sect/doc1.html"), Content: []byte("---\nmarkup: markdown\n---\n# title\nsome *content*")},
		{Name: filepath.FromSlash("sect/doc2.html"), Content: []byte("<!doctype html><html><body>more content</body></html>")},
		{Name: filepath.FromSlash("sect/doc3.md"), Content: []byte("# doc3\n*some* content")},
		{Name: filepath.FromSlash("sect/doc4.md"), Content: []byte("---\ntitle: doc4\n---\n# doc4\n*some content*")},
		{Name: filepath.FromSlash("sect/doc3/img1.png"), Content: []byte("‰PNG  ��� IHDR����������:~›U��� IDATWcø��ZMoñ����IEND®B`‚")},
		{Name: filepath.FromSlash("sect/img2.gif"), Content: []byte("GIF89a��€��ÿÿÿ���,�������D�;")},
		{Name: filepath.FromSlash("sect/img2.spf"), Content: []byte("****FAKE-FILETYPE****")},
		{Name: filepath.FromSlash("doc7.html"), Content: []byte("<html><body>doc7 content</body></html>")},
		{Name: filepath.FromSlash("sect/doc8.html"), Content: []byte("---\nmarkup: md\n---\n# title\nsome *content*")},
	}

	viper.Set("DefaultExtension", "html")
	viper.Set("verbose", true)

	s := &Site{
		Source:   &source.InMemorySource{ByteSource: sources},
		targets:  targetList{page: &target.PagePub{UglyURLs: true, PublishDir: "public"}},
		Language: helpers.NewLanguage("en"),
	}

	if err := buildAndRenderSite(s,
		"_default/single.html", "{{.Content}}",
		"head", "<head><script src=\"script.js\"></script></head>",
		"head_abs", "<head><script src=\"/script.js\"></script></head>"); err != nil {
		t.Fatalf("Failed to render site: %s", err)
	}

	tests := []struct {
		doc      string
		expected string
	}{
		{filepath.FromSlash("public/sect/doc1.html"), "\n\n<h1 id=\"title\">title</h1>\n\n<p>some <em>content</em></p>\n"},
		{filepath.FromSlash("public/sect/doc2.html"), "<!doctype html><html><body>more content</body></html>"},
		{filepath.FromSlash("public/sect/doc3.html"), "\n\n<h1 id=\"doc3\">doc3</h1>\n\n<p><em>some</em> content</p>\n"},
		{filepath.FromSlash("public/sect/doc3/img1.png"), string([]byte("‰PNG  ��� IHDR����������:~›U��� IDATWcø��ZMoñ����IEND®B`‚"))},
		{filepath.FromSlash("public/sect/img2.gif"), string([]byte("GIF89a��€��ÿÿÿ���,�������D�;"))},
		{filepath.FromSlash("public/sect/img2.spf"), string([]byte("****FAKE-FILETYPE****"))},
		{filepath.FromSlash("public/doc7.html"), "<html><body>doc7 content</body></html>"},
		{filepath.FromSlash("public/sect/doc8.html"), "\n\n<h1 id=\"title\">title</h1>\n\n<p>some <em>content</em></p>\n"},
	}

	for _, test := range tests {
		file, err := hugofs.Destination().Open(test.doc)
		if err != nil {
			t.Fatalf("Did not find %s in target.", test.doc)
		}

		content := helpers.ReaderToString(file)

		if content != test.expected {
			t.Errorf("%s content expected:\n%q\ngot:\n%q", test.doc, test.expected, content)
		}
	}

}
开发者ID:tarsisazevedo,项目名称:hugo,代码行数:60,代码来源:handler_test.go


示例18: doTestMenuWithUnicodeURLs

func doTestMenuWithUnicodeURLs(t *testing.T, canonifyURLs, uglyURLs bool) {
	viper.Reset()
	defer viper.Reset()

	viper.Set("CanonifyURLs", canonifyURLs)
	viper.Set("UglyURLs", uglyURLs)

	s := setupMenuTests(t, MENU_PAGE_SOURCES)

	unicodeRussian := findTestMenuEntryByID(s, "unicode", "unicode-russian")

	expectedBase := "/%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0"

	if !canonifyURLs {
		expectedBase = "/Zoo" + expectedBase
	}

	var expected string
	if uglyURLs {
		expected = expectedBase + ".html"
	} else {
		expected = expectedBase + "/"
	}

	assert.Equal(t, expected, unicodeRussian.URL, "uglyURLs[%t]", uglyURLs)
}
开发者ID:krig,项目名称:hugo,代码行数:26,代码来源:menu_test.go


示例19: server

func server(cmd *cobra.Command, args []string) {
	InitializeConfig()

	if BaseUrl == "" {
		BaseUrl = "http://localhost"
	}

	if !strings.HasPrefix(BaseUrl, "http://") {
		BaseUrl = "http://" + BaseUrl
	}

	if serverAppend {
		viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/")+":"+strconv.Itoa(serverPort))
	} else {
		viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/"))
	}

	build(serverWatch)

	// Watch runs its own server as part of the routine
	if serverWatch {
		jww.FEEDBACK.Println("Watching for changes in", helpers.AbsPathify(viper.GetString("ContentDir")))
		err := NewWatcher(serverPort)
		if err != nil {
			fmt.Println(err)
		}
	}

	serve(serverPort)
}
开发者ID:vinchu,项目名称:hugo,代码行数:30,代码来源:server.go


示例20: initConfig

// initConfig reads in config file and ENV variables if set.
func initConfig() {

	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".grnl") // name of config file (without extension)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("Error using config file %q\n%q", viper.ConfigFileUsed(), err)
	}

	if db != "" {
		viper.Set("db", db)
	}

	if editor != "" {
		viper.Set("editor", editor)
	}

	if dateFormat != "" {
		viper.Set("dateFormat", dateFormat)
	}
}
开发者ID:jzorn,项目名称:grnl,代码行数:28,代码来源:grnl.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang viper.SetConfigFile函数代码示例发布时间:2022-05-28
下一篇:
Golang viper.Reset函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap