美文网首页
golang 读取ini文件

golang 读取ini文件

作者: quanCN | 来源:发表于2021-08-10 14:37 被阅读0次

ini文件简介

INI文件的命名来源,是取自英文“初始(Initial)”的首字缩写,正与它的用途——初始化程序相应。INI文件是一种无固定标准格式的配置文件。它以简单的文字与简单的结构组成,常常使用在Windows操作系统上,许多程序也会采用INI文件做为配置文件之用。wiki

ini文件格式

  • keys
    name=value
    
  • Sections
    [section]
    
  • example
    ; last modified 1 April 2001 by John Doe
    [owner]
    name=John Doe
    organization=Acme Products
    
    [database]
    server=192.0.2.42 ; use IP address in case network name resolution is not working
    port=143
    file="acme payroll.dat"
    

go读取ini

  • config.ini
    version = 1.0.0
    width   = 75.3
    
    [mysql]
    host     = 127.0.0.1
    port     = 8080
    username = root
    password = 111111
    database = test
    
  • go
    package main
    
    import (
        "fmt"
        "gopkg.in/ini.v1"
        "log"
    )
    
    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")
    }
    
    func getErr(msg string, err error){
        if err != nil{
            log.Printf("%v err->%v\n", msg, err)
        }
    }
    

相关文章

网友评论

      本文标题:golang 读取ini文件

      本文链接:https://www.haomeiwen.com/subject/tgnxbltx.html