INI

INI文件是Initialization File的缩写,意思为"配置文件;初始化文件;",以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为INI,故名。

环境

在主程序文件目录下创建"my.ini"文件内容如下

app_mode = development

[paths]
data = /home/git/grafana

[server]
protocol = http
http_port = 9999
enforce_domain = true

开始使用

package main

import (
    "fmt"
    "github.com/go-ini/ini"
)

func main() {
    // 读取配置文件
    cfg, err := ini.Load("my.ini")
    if err != nil {
        panic(err)
    }
    //读取
    //读取app_mode
    fmt.Println("app_mode:", cfg.Section("").Key("app_mode"))
    //读取paths.data
    fmt.Println("paths.data:", cfg.Section("paths").Key("data").String())
    //读取server.protocol并限制值
    //如果没有值或值错误则使用"http"
    fmt.Println("server.protocol:", cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))
    //读取时进行类型转换,MustInt()可以存放默认值,如果转换失败则使用里面的值
    fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt())

    //修改
    //修改app_mode的值为production
    cfg.Section("").Key("app_mode").SetValue("production")
    //修改完毕写入"my.ini.local"文件
    cfg.SaveTo("my.ini.local")
}
最后修改:2022 年 12 月 17 日
如果觉得我的文章对你有用,请随意赞赏