go-ini的用法

0 需求分析

  • go语言读取ini的配置文件
  • 获取指定分区的对象或名称
  • 获取指定分区下的所有对象或名称
  • 自动类型转换(读取的3306直接为int类型)
  • 结构体映射,通过结构体直接访问配置文件信息
    参考链接:
https://blog.csdn.net/Guzarish/article/details/118626693?spm=1001.2101.3001.4242.2&utm_relevant_index=4

标题1 环境搭建

首先,安装go-ini的安装包,默认安装到GOPATH中

go get gopkg.in/ini.v1

其次,我们需要在任意目录创建两个文件(my.ini和main.go)
在这里插入图片描述
my.ini文件内容如下:

# possible values : production, development
app_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 use
http_port = 9999
 
enforce_domain=bool
[mysql]
Sql_port = 3306
USER = root
PASSWORD = root

[ip]
A03=192.168.1.203
A04=192.168.1.204
A05=192.168.1.205
A06=192.168.1.206

2 结果展示

在这里插入图片描述

3 源代码

main.go

package main

import (
	"fmt"
	"os"

	"gopkg.in/ini.v1"
)

type sqlStruct struct {
	Sql_port int
	USER     string
	PASSWORD string
}

func main() {
	//参考网页 go ini的中文解释
	//https://blog.csdn.net/Guzarish/article/details/118626693?spm=1001.2101.3001.4242.2&utm_relevant_index=4
	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("******************************")

	// fmt.Println("Data Path:", cfg.Section("paths").KeyStrings()[0])
	// fmt.Println("Data Path:", cfg.Section("paths").Keys()[0])
	//fmt.Printf("%T\n", cfg.Section("paths").KeyStrings())

	// 试一试自动类型转换
	fmt.Printf("Port Number: (%[1]T) %[2]d\n", cfg.Section("server").Key("http_port").MustInt(), 23)
	fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool())
	fmt.Println("******************************")

	//获取所有分区对象或名称
	values := cfg.Section("ip").Keys()
	keys := cfg.Section("ip").KeyStrings()
	fmt.Printf("ip keys %v\n", keys)
	fmt.Printf("ip values %v\n", values)
	fmt.Println("******************************")

	//结构体映射
	mySql := new(sqlStruct)
	err = cfg.Section("mysql").MapTo(mySql)
	if err != nil {
		return
	}
	fmt.Printf("mySql.PASSWORD (%[1]T) %[1]v\n", mySql.PASSWORD)
	fmt.Printf("mySql.Sql_port (%[1]T) %[1]v\n", mySql.Sql_port)
	fmt.Println("******************************")

	// // 修改某个值然后进行保存
	// cfg.Section("").Key("app_mode").SetValue("production")
	// cfg.SaveTo("my.ini.local")
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

唐维康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值