app.conf配置项读取
app.conf文件
appname = "hellow"
httpport = 8080
runmode = dev[dev]
httpport = 8080
[prod]
httpport = 8088
[test]
httpport = 8888
beego.AppConfig.Bool("key")
beego.AppConfig.String("key")
beego.AppConfig.Int("key")
beego.AppConfig.Int64("key")
beego.AppConfig.Float("key")
appname := beego.AppConfig.String("app name")
port, err := beego.AppConfig.Int("httpport")
...
section 操作
在默认情况下配置app.conf中会有配置项runmode,runmode对应的配置就是section,示例中的runmode为dev则读取的httpport为8080
testPort, _ := beego.AppConfig.Int(“test::httpport”)
section::key的读取
通过String(“section::key”)可以读取指定section的key所对应的值,上例中想读取8080,可以这样操作:String(“dev::httpport”)
json格式的配置读取
先导入"github.com/astaxie/beego/config"
创建test.json
{
"dev":{
"appname" : "hellow",
"runmode" : "dev",
"httpport" : 81
}
}
以下代码
conf, err := config.NewConfig("json", "conf/test.json")
if err == nil {
val := conf.String("dev::app name”) //初始化配置
fmt.Println("val: ", val)
port, _ := conf.Int("dev::httpport")
fmt.Println("val: ", port)
} else {
fmt.Println(err)
}
分组配置
在conf下的app.conf 加入include “../custom/app.conf”
注意:相同的配置项后面的会覆盖前面的。
config模块详解
config模块初始化
先导入”github.com/astaxie/beego/config”包,
接下来初始化config(解析器对象)
iniconf, err := config.NewConfig("ini", "testini.conf")
然后通过对象获取数据
iniconf.String("app name")
解析器对象支持的函数有如下:
Set(key, val string) error // 使用ini配置文件时支持
section::key. String(key string) string
// 使用ini或json配置文件时支持section::key; Int,Int64,Bool,Float,DIY同样支持.
Strings(key string) []string // 获取字符串切片
Int(key string) (int, error)
Int64(key string) (int64, error)
Bool(key string) (bool, error)
Float(key string) (float64, error)
DefaultString(key string, defaultval string) string // 使用ini或json配置文件时支持section::key; Int,Int64,Bool,Float,DIY同样支持.
DefaultStrings(key string, defaultval []string) []string // 获取字符串切片
DefaultInt(key string, defaultval int) int
DefaultInt64(key string, defaultval int64) int64
DefaultBool(key string, defaultval bool) bool
DefaultFloat(key string, defaultval float64) float64
DIY(key string) (interface{}, error)
GetSection(section string) (map[string]string, error)
SaveConfigFile(filename string) error
ini配置文件支持section操作,key通过section:key的方式获取
Default类型的API,key配置项不存在,则读取default value,存在的话则读取配置项对应的值