init
This commit is contained in:
19
myconf/conf.go
Normal file
19
myconf/conf.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package myconf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func Init(confPath string, conf interface{}) {
|
||||
v := viper.New()
|
||||
v.SetConfigFile(confPath)
|
||||
err := v.ReadInConfig()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("读取配置文件失败 %s", err))
|
||||
}
|
||||
err = v.Unmarshal(conf)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("解析配置文件失败 %s", err))
|
||||
}
|
||||
}
|
||||
25
myconf/conf_test.go
Normal file
25
myconf/conf_test.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package myconf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConf(t *testing.T) {
|
||||
type Config struct {
|
||||
App struct {
|
||||
Name string
|
||||
Addr string
|
||||
Port int
|
||||
}
|
||||
|
||||
Redis struct {
|
||||
Addr string
|
||||
Db int
|
||||
}
|
||||
}
|
||||
|
||||
var config = &Config{}
|
||||
Init("test.yaml", config)
|
||||
fmt.Printf("%+v\n", config)
|
||||
}
|
||||
8
myconf/test.yaml
Normal file
8
myconf/test.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
App:
|
||||
Name: "server"
|
||||
Addr: 127.0.0.1
|
||||
Port: 9000
|
||||
|
||||
Redis:
|
||||
Addr: "127.0.0.1:6379"
|
||||
Db: 15
|
||||
Reference in New Issue
Block a user