go get gopkg.in/ini.v1
    https://ini.unknwon.cn/docs
    我们编辑 my.ini 文件并输入以下内容

    1. # possible values : production, development
    2. app_mode = development
    3. [paths]
    4. # Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
    5. data = /home/git/grafana
    6. [server]
    7. # Protocol (http or https)
    8. protocol = http
    9. # The http port to use
    10. http_port = 9999
    11. # Redirect to correct domain if host header does not match domain
    12. # Prevents DNS rebinding attacks
    13. enforce_domain = true

    下来我们需要编写 main.go 文件来操作刚才创建的配置文件。

    1. package main
    2. import (
    3. "fmt"
    4. "os"
    5. "gopkg.in/ini.v1"
    6. )
    7. func main() {
    8. cfg, err := ini.Load("my.ini")
    9. if err != nil {
    10. fmt.Printf("Fail to read file: %v", err)
    11. os.Exit(1)
    12. }
    13. // 典型读取操作,默认分区可以使用空字符串表示
    14. fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String())
    15. fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())
    16. // 我们可以做一些候选值限制的操作
    17. fmt.Println("Server Protocol:",
    18. cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))
    19. // 如果读取的值不在候选列表内,则会回退使用提供的默认值
    20. fmt.Println("Email Protocol:",
    21. cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))
    22. // 试一试自动类型转换
    23. fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt(9999))
    24. fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool(false))
    25. // 差不多了,修改某个值然后进行保存
    26. cfg.Section("").Key("app_mode").SetValue("production")
    27. cfg.SaveTo("my.ini.local")
    28. }