学校文化建设网站,网页seo,如何做网络销售平台,运维网站建设点击上方蓝色“Go语言中文网”关注我们#xff0c;领全套Go资料#xff0c;每天学习 Go 语言如果你使用 INI 作为系统的配置文件#xff0c;那么一定会使用这个库吧。没错#xff0c;它就是号称地表 最强大、最方便 和 最流行 的 Go 语言 INI 文件操作库#xff1a;https:… 点击上方蓝色“Go语言中文网”关注我们领全套Go资料每天学习 Go 语言如果你使用 INI 作为系统的配置文件那么一定会使用这个库吧。没错它就是号称地表 最强大、最方便 和 最流行 的 Go 语言 INI 文件操作库https://github.com/go-ini/ini。该项目的作者也是很多 Go 语言爱好者熟悉的无闻大师。讲真文档都写的很好很用心。官方网站https://ini.unknwon.io/功能特性支持覆盖加载多个数据源([]byte、文件和 io.ReadCloser)支持递归读取键值支持读取父子分区支持读取自增键名支持读取多行的键值支持大量辅助方法支持在读取时直接转换为 Go 语言类型支持读取和 写入 分区和键的注释轻松操作分区、键值和注释在保存文件时分区和键值会保持原有的顺序下载安装最低要求安装 Go 语言版本为 1.6。$ go get -u gopkg.in/ini.v1开始使用我们将通过一个非常简单的例子来了解如何使用。首先我们需要在任意目录创建两个文件(my.ini 和 main.go)在这里我们选择 /tmp/ini 目录。$ mkdir -p /tmp/ini$ cd /tmp/ini$ touch my.ini main.go$ tree ..├── main.go└── my.ini0 directories, 2 files现在我们编辑 my.ini 文件并输入以下内容(部分内容来自 Grafana)。# possible values : production, developmentapp_mode development[paths]# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)data /home/git/grafana[server]# Protocol (http or https)protocol http# The http port to usehttp_port 9999# Redirect to correct domain if host header does not match domain# Prevents DNS rebinding attacksenforce_domain true很好接下来我们需要编写 main.go 文件来操作刚才创建的配置文件。package mainimport (fmtosgopkg.in/ini.v1)func main() { cfg, err : ini.Load(my.ini)if err ! nil { fmt.Printf(Fail to read file: %v, err) os.Exit(1) }// 典型读取操作默认分区可以使用空字符串表示 fmt.Println(App Mode:, cfg.Section().Key(app_mode).String()) fmt.Println(Data Path:, cfg.Section(paths).Key(data).String())// 我们可以做一些候选值限制的操作 fmt.Println(Server Protocol:, cfg.Section(server).Key(protocol).In(http, []string{http, https}))// 如果读取的值不在候选列表内则会回退使用提供的默认值 fmt.Println(Email Protocol:, cfg.Section(server).Key(protocol).In(smtp, []string{imap, smtp}))// 试一试自动类型转换 fmt.Printf(Port Number: (%[1]T) %[1]d\n, cfg.Section(server).Key(http_port).MustInt(9999)) fmt.Printf(Enforce Domain: (%[1]T) %[1]v\n, cfg.Section(server).Key(enforce_domain).MustBool(false))// 差不多了修改某个值然后进行保存 cfg.Section().Key(app_mode).SetValue(production) cfg.SaveTo(my.ini.local)}运行程序我们可以看下以下输出$ go run main.goApp Mode: developmentData Path: /home/git/grafanaServer Protocol: httpEmail Protocol: smtpPort Number: (int) 9999Enforce Domain: (bool) true$ cat my.ini.local# possible values : production, developmentapp_mode production[paths]# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)data /home/git/grafana...完美这个例子很简单展示的也只是极其小部分的功能想要完全掌握还需要多读多看毕竟学无止境嘛。推荐阅读【每日一库】解析和提交 HTML 表单的库gosubmit喜欢本文的朋友欢迎关注“Go语言中文网”Go语言中文网启用微信学习交流群欢迎加微信274768166投稿亦欢迎