使用 go-ini 解析配置文件 本文只介绍实际项目开发中最常用到的功能,详细说明请参考《go-ini使用文档》 。
1 下载、安装 go-ini
2 go-ini 解析配置文件 Demo 2.1 配置文件格式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 app_mode = development [paths] data = /home/git/grafana [server] protocol = http http_port = 9999 enforce_domain = true
和大多数配置文件一样,以键值对 的形式表示配置信息
当文本中出现一行形如 “[example_section_name]” ,表示新建一个分区,之后的配置信息会和这个分区关联,除非另起一个新分区。
文件最开头的部分,如果没有显式地指明分区,则这些配置信息属于默认分区。
2.2 从数据源加载 1 cfg, err := ini.Load("my.ini" )
加载指定路径配置文件的数据,并解析。
2.3 获取、写入配置值 2.3.1 读取指定分区下的某个配置项 1 2 3 fmt.Println("App Mode:" , cfg.Section("" ).Key("app_mode" ).String()) fmt.Println("Data Path:" , cfg.Section("paths" ).Key("data" ).String())
2.3.2 候选值限制 1 2 3 fmt.Println("Server Protocol:" , cfg.Section("server" ).Key("protocol" ).In("http" , []string {"http" , "https" })) fmt.Println("Email Protocol:" , cfg.Section("server" ).Key("protocol" ).In("smtp" , []string {"imap" , "smtp" }))
如果读取的值不在候选值列表中,则用默认值替代。
2.2.3 类型转换 1 2 fmt.Printf("Port Number: (%[1]T) %[1]d\n" , cfg.Section("server" ).Key("http_port" ).MustInt(9999 )) fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n" , cfg.Section("server" ).Key("enforce_domain" ).MustBool(false ))
2.2.4 修改配置值 1 cfg.Section("" ).Key("app_mode" ).SetValue("production" )
2.2.5 保存配置文件 1 cfg.SaveTo("my.ini.local" )
调用 SaveTo 方法将配置文件保存到指定路径。
2.4 完整代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package mainimport ( "fmt" "os" "gopkg.in/ini.v1" ) func main () { cfg, err := ini.Load("my.ini" ) if err != nil { fmt.Printf("Fail to read file:%v\n" , err) os.Exit(1 ) } fmt.Println("App Mode:" , cfg.Section("" ).Key("app_mode" ).String()) fmt.Println("Data Path:" , cfg.Section("paths" ).Key("data" ).String()) fmt.Println("Server Protocol:" , cfg.Section("server" ).Key("protocol" ).In("http" , []string {"http" , "https" })) fmt.Println("Email Protocol:" , cfg.Section("server" ).Key("protocol" ).In("smtp" , []string {"imap" , "smtp" })) fmt.Printf("Port Number: (%[1]T) %[1]d\n" , cfg.Section("server" ).Key("http_port" ).MustInt(9999 )) fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n" , cfg.Section("server" ).Key("enforce_domain" ).MustBool(false )) cfg.Section("" ).Key("app_mode" ).SetValue("production" ) cfg.SaveTo("my.ini.local" ) }
2.5 执行效果 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 $ go run ini.go App Mode: development Data Path: /home/git/grafana Server Protocol: http Email Protocol: smtp Port Number: (int) 9999 Enforce Domain: (bool) true $ cat ./my.ini.local app_mode = production [paths] data = /home/git/grafana [server] protocol = http http_port = 9999 enforce_domain = true