golang init 文件处理
主要是基于go-ini 提供基于配置的管理
环境准备
- 项目结构
├── README.md
├── go.mod
├── go.sum
├── main.go
├── server.ini
└── server2.ini
- go.mod
module myini
go 1.14
require gopkg.in/ini.v1 v1.61.0
- main.go
package main
import (
"log"
"time"
"gopkg.in/ini.v1"
)
type serverConf struct {
AppName string `ini:"app_name"`
Admin `init:"admin"`
UI `init:"ui"`
}
type Admin struct {
UserName string `ini:"username"`
Password string `ini:"password"`
}
type UI struct {
Addr string `ini:"addr"`
Path string
}
type Note struct {
Content string `ini:"content"`
Cities []string `ini:"cities"`
}
type Person struct {
Name string `ini:"name"`
Age int `ini:"age"`
Male bool
Born time.Time
Note
Created time.Time `ini:"-"`
}
func demo1() {
cfg, err := ini.Load("server.ini")
if err != nil {
log.Println("error", err.Error())
}
p := new(Person)
err = cfg.MapTo(p)
log.Println(p.Name)
err = ini.MapTo(p, "mycopy.init")
n := new(Note)
err = cfg.Section("Note").MapTo(n)
log.Println(n.Content, n.Cities)
}
func demo2() {
cfg, err := ini.InsensitiveLoad("server2.ini")
if err != nil {
log.Println("error", err.Error())
}
s := new(serverConf)
err = cfg.MapTo(s)
log.Println("demo", s.AppName, s.Admin.Password, s.UI.Path)
admin := new(Admin)
err = cfg.Section("admin").MapTo(admin)
cfg.Section("oauth").NewKey("dalongdemo", "ddddd")
log.Println(admin.Password, admin.UserName)
cfg.SaveTo("demoapp.ini")
}
func main() {
demo2()
}
- server2.ini
app_name = "dalongdemo"
[admin]
username = "dalong"
password = "demoapp"
[ui]
addr = "0.0.0.0:8080"
path = "/web"
- 运行效果
go run main.go
说明
go-ini 是一个很不错的选择,同时也是一个很不错的ini配置处理工具,grafana 内部就使用了go-ini
参考资料
https://ini.unknwon.io/docs/intro/getting_started
https://github.com/go-ini/ini