golang 读取ini文件

package main

import (
    "fmt"
    "gopkg.in/ini.v1"
    "log"
    "time"
)

func main() {
    cfg, err := ini.Load("config.ini")
    getErr("load config", err)

    // 遍历所有的section
    for _, v := range cfg.Sections() {
        fmt.Println(v.KeyStrings())
    }

    // 获取默认分区的key
    fmt.Println(cfg.Section("").Key("version").String()) // 将结果转为string
    fmt.Println(cfg.Section("").Key("width").Float64())  // 将结果转为float

    // 获取mysql分区的key
    fmt.Println(cfg.Section("mysql").Key("host").String()) // 将结果转为string
    fmt.Println(cfg.Section("mysql").Key("port").Int())    // 将结果转为int

    // 如果读取的值不在候选列表内,则会回退使用提供的默认值
    fmt.Println("Server Protocol:",
        cfg.Section("mysql").Key("port").In("80", []string{"5555", "8080"}))

    // 自动类型转换
    fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("mysql").Key("port").MustInt(9999))
    fmt.Printf("Database Name: (%[1]T) %[1]s\n", cfg.Section("mysql").Key("database").MustString("test"))

    // 修改某个值然后进行保存
    cfg.Section("").Key("version").SetValue("2.0.0")
    cfg.SaveTo("config.ini")
    time.Sleep(1000 * time.Second)
}

func getErr(msg string, err error) {
    if err != nil {
        log.Printf("%v err->%v\n", msg, err)
    }
}

 

posted @ 2022-02-10 11:15  酷酷的城池  阅读(524)  评论(0编辑  收藏  举报