php做网站界面代码,江门网站推广哪家好,免费照片编辑器,沈阳seo推广公司本文对 ini 文件进行解析。 概述
某Delphi项目需要做一些额外的配置#xff0c;因为原本的配置文件是ini格式的#xff0c;为不影响已有代码#xff0c;而且delphi读取解析ini比较简单#xff0c;考虑到兼容性#xff0c;最终还是新建单独的ini配置文件并解析。为了对比数…本文对 ini 文件进行解析。 概述
某Delphi项目需要做一些额外的配置因为原本的配置文件是ini格式的为不影响已有代码而且delphi读取解析ini比较简单考虑到兼容性最终还是新建单独的ini配置文件并解析。为了对比数据一致性除了Delphi工程外还在另一golang工程实现相同的算法所用的配置文件完全相同。本文使用 Golang 解析 ini。
测试
github仓库在此下载
go get gopkg.in/ini.v1go mod vendor # 加入vendor截取发文时最新版本为v1.67.0。
引入包代码片段
import (ini gopkg.in/ini.v1
)配置文件config.ini文件内容
# ini 测试样例[section1]
sec1 110 210 ddd 99 | 133 135 1 2 1588 1509 | 310-410
sec2 late \n lee | Jim Kent[section2]
id 250
arrint 1 | 2 | 3
arrstr apple, apple2, apple3
测试代码
package testimport (fmttestinggopkg.in/ini.v1
)var (cfgFile string config.ini
)func TestIni(t *testing.T) {fmt.Println(test of ini...)// 加载cfg, err : ini.Load(cfgFile)if err ! nil {fmt.Printf(Fail to read file: %v, err)return}// 读一节mySection : cfg.Section(section1)fmt.Println(keystrings:, mySection.KeyStrings())// 解析for _, key : range mySection.KeyStrings() {fmt.Printf(key: [%v]\nvalue: , key)values : mySection.Key(key).Strings(|)for _, item : range values {fmt.Printf([%v] , item)}fmt.Printf(\n--------\n)}// 按单个字符串strVlaue : cfg.Section(section2).Key(id).Value()fmt.Printf(section2.id value: %v\n, strVlaue)// 数值以|分隔arrVlaueInt : cfg.Section(section2).Key(arrint).ValidInts(|)fmt.Printf(section2.arrint value: %v\n, arrVlaueInt)// 字符串以,分隔arrVlaueStr : cfg.Section(section2).Key(arrstr).Strings(,)fmt.Printf(section2.arrstr value: %v\n, arrVlaueStr)// 写入inicfg.Section().Key(name).SetValue(foobar)cfg.Section(info).Key(appVer).SetValue(1.3)cfg.Section(info).Key(author).SetValue(Late Lee)// 另起文件cfg.SaveTo(output.ini)
}输出结果
test of ini...
keystrings: [sec1 sec2]
key: [sec1]
value: [110 210 ddd 99] [133 135 1 2 1588 1509] [310-410]
--------
key: [sec2]
value: [late \n lee] [Jim Kent]
--------
section2.id value: 250
section2.arrint value: [1 2 3]
section2.arrstr value: [apple apple2 apple3]新生成的文件output.ini内容
name foobar# ini 测试样例
[section1]
sec1 110 210 ddd 99 | 133 135 1 2 1588 1509 | 310-410
sec2 late \n lee | Jim Kent[section2]
id 250
arrint 1 | 2 | 3
arrstr apple, apple2, apple3[info]
appVer 1.3
author Late Lee小结
除了维护有一定历史的工程外用到ini外笔者一般会选择其它格式因此测试代码较简单。就目前看主要还是yaml。考虑到兼容性也会用到xml。
相关文章: