golang viper_config

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang viper_config相关的知识,希望对你有一定的参考价值。

// Author: Mjy
// Create Date: 2018-11-23
package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"strings"
)

type ApiConfig struct {
	RunMode      string `mapstructure:"runmode"`
	Addr         string `mapstructure:"addr"`
	Port         int    `mapstructure:"port"`
	Name         string `mapstructure:"name"`
	Url          string `mapstructure:"url"`
	MaxPingCount int    `mapstructure:"max_ping_count"`
}

var Config = &ApiConfig{}

func InitConfig(cfg string) error {
	c := viper.New()
	if err := initConfig(cfg, c); err != nil {
		return err
	}
	if err := c.UnmarshalExact(Config); err != nil {
		return err
	}
	c.WatchConfig()
	c.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:" + e.Name)
		c.Unmarshal(Config)
	})
	return nil
}

func initConfig(cfg string, c *viper.Viper) error {
	c.SetConfigType("yaml")
	if cfg == "" {
		c.SetConfigFile("/Users/majianyu/Code/go/GoLandProjects/dsers/src/api/conf/config.yaml")
	} else {
		c.SetConfigFile(cfg)
	}
	c.AutomaticEnv()
	c.SetEnvPrefix("APISERVER")
	replacer := strings.NewReplacer(".", "_")
	c.SetEnvKeyReplacer(replacer)

	if err := c.ReadInConfig(); err != nil {
		return err
	}
	return nil
}
runmode: debug
addr: 127.0.0.1
port: 8080
name: api
url: http://127.0.0.1:8080
max_ping_count: 10
// Author: Mjy
// Create Date: 2018-11-23
package main

import (
	"api/config"
	"github.com/spf13/pflag"
)

var cfg = pflag.StringP("config", "c", "", "apiserver config file path.")

func main() {
	pflag.Parse()
	if err := config.InitConfig(*cfg); err != nil {
		panic(err)
	}
}

json [Golang] golang #golang #snippets中有用的片段

[ fmt ](https://golang.org/pkg/fmt/)
-------
Print any `type`(struct,maps,primitives) with the `key` name 

``` 
fmt.Printf("\n [key] :%+v \n", [value]) 

```

Print Error  

``` 
fmt.Errorf(" \nError: %s", err.Error()) 

```

[ log ](https://golang.org/pkg/log/)
-------------

Print any `type`(struct,maps,primitives) with the `key` name 

``` 
log.Printf("\n [key] :%+v \n", [value]) 

```


[ http  ](https://golang.org/pkg/log/)
-------------

http middleware 

```  
func [middlewareName](h http.Handler) http.Handler {
              return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
              // Do things before request 
           	
              nextMiddleware.ServeHTTP(w, r)
              // Do things after request	  
              })
          } 
```
{
         "http Middleware declaration": {
		"prefix": "md",
		"body": ["func $1(${2:nextMiddleware} http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(${3:w} http.ResponseWriter, ${4:r} *http.Request) {\n\t $5\n\t nextMiddleware.ServeHTTP(${3:w}, ${4:r})\n\t 	  $6\n\t})\n}"],
		"description": "Snippet for http middleware declaration"
	},

	"log.Printf()": {
		"prefix": "lf",
		"body": [
			"log.Printf(\"\\n## ${1:text} ##: %+v\\n\", ${2:value})"
		],
		"description": "log.Printf()"
	},
	"fmt.Printf()": {
		"prefix": "ff",
		"body": [
			"fmt.Printf(\"\\n## ${1:text} ## :%+v \\n\", ${2:value})",
		],
		"description": "log.Printf()"
	}
}

以上是关于golang viper_config的主要内容,如果未能解决你的问题,请参考以下文章

Golang 入门

Golang入门到项目实战 第一个golang应用

golang编译androidso无法加载

golang如何打印内存内容

Golang入门到项目实战 golang匿名函数

json [Golang] golang #golang #snippets中有用的片段