0

go ini库之go-ini

 2 years ago
source link: https://blog.51cto.com/u_3764469/5610676
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

go ini库之go-ini

精选 原创

zzxiaoma 2022-08-23 08:57:39 博主文章分类:go ©著作权

文章标签 mysql 加载 数据源 文章分类 Go语言 编程语言 yyds干货盘点 阅读数172

一、安装go get gopkg.in/ini.v1

doc.ini

mode = development

[mysql]

default-character-set=utf8

[server]

ip = 127.0.0.1

port = abc

获取内容如下

package main

import (
"fmt"
"os"
"gopkg.in/ini.v1"
)

func main() {
cfg, err := ini.Load("doc.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
fmt.Println(cfg.Section("").Key("mode").Value())
fmt.Println("Mode:", cfg.Section("").Key("mode").String())
fmt.Println("mysql:", cfg.Section("mysql").Key("default-character-set").String())
fmt.Println(cfg.Section("server").Key("port").MustInt(8888))
fmt.Println(
cfg.Section("server").Key("ip").In("192.168.0.1", []string{"localhost", "192.168.0.1"}))

}

通过Load方法加载ini文件,通过cfg.Section("")获取默认分区,也就是没有显式标明的中括号下面的数据,接着Key方法就可以获取到对应的值,再通过String()方法转成字符串。

通过.MustInt(8888)方法表明如果获取到的值不是int,就是用8888来代替。使用In可以提供候选值,如果上面的string切片,只能是localhost或192.168.0.1,ip信息不是这2项,就是把ip的值当做192.168.0.1。

在加载多个数据源时,如果某一个键在一个或多个数据源中出现,则会出现数据覆写。也就是加载多个文件时,文件中的分区和键不要同时一样。

ini.Load("doc.ini", "doc1.ini")

如果ini文件中不是所有的内容都是键值对,也就是只有键没有值,如果想忽略这些内容使用

cfg, err := ini.LoadSources(ini.LoadOptions{
SkipUnrecognizableLines: true,
}, "other.ini")

修改保存文件使用

cfg.Section("").Key("mode").SetValue("production")
err = cfg.SaveTo("doc.ini")

忽略键名大小写

cfg, err := ini.InsensitiveLoad("doc.ini")

判断值是否存在

yes := cfg.Section("").HasValue("test value")
  • 收藏
  • 评论
  • 分享
  • 举报

上一篇:go基础之读取ini


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK