在 Go 语言中,可以使用第三方库 'go-ini/ini' 来读取和修改 INI 文件。首先需要安装该库,可以使用以下命令进行安装:

go get -u gopkg.in/ini.v1

接下来可以使用以下代码来读取 INI 文件:

package main

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

func main() {
	cfg, err := ini.Load("config.ini")
	if err != nil {
		fmt.Printf("Failed to read file: %v", err)
		return
	}

	// 读取指定 section 的值
	section := cfg.Section("database")
	host := section.Key("host").String()
	port := section.Key("port").String()

	fmt.Printf("Host: %s\n", host)
	fmt.Printf("Port: %s\n", port)
}

上述代码中,'config.ini' 是 INI 文件的路径,'database' 是要读取的 section 名称,'host' 和 'port' 是要读取的 key 名称。

如果需要修改 INI 文件的值,可以使用以下代码:

package main

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

func main() {
	cfg, err := ini.Load("config.ini")
	if err != nil {
		fmt.Printf("Failed to read file: %v", err)
		return
	}

	// 修改指定 section 的值
	section := cfg.Section("database")
	section.Key("host").SetValue("localhost")
	section.Key("port").SetValue("3306")

	err = cfg.SaveTo("config.ini")
	if err != nil {
		fmt.Printf("Failed to save file: %v", err)
		return
	}

	fmt.Println("INI file updated successfully.")
}

上述代码中,首先读取并加载 INI 文件。然后使用 'Section' 方法获取指定的 section,再使用 'Key' 方法获取指定的 key,并使用 'SetValue' 方法修改其值。最后使用 'SaveTo' 方法将修改后的 INI 文件保存到磁盘。

注意,以上代码只是示例,实际使用时需要根据你的 INI 文件的结构和需求进行相应的修改。


原文地址: https://www.cveoy.top/t/topic/qxxG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录