INI files are a popular format for configuration files due to their simplicity and readability. In Go, the go-ini package offers a convenient way to read and write data in INI file format. This article walks you through using go-ini to work with INI files.
Installing go-ini
To get started, you'll first need to install the go-ini package. You can do this using go get:
go get github.com/go-ini/iniReading an INI File
Let's begin by reading an INI file. Suppose you have an INI file named config.ini with the following content:
[server]
port = 8080
[redis]
host = localhost
port = 6379
Here's how you can read it using the go-ini package:
package main
import (
"fmt"
"log"
"github.com/go-ini/ini"
)
func main() {
cfg, err := ini.Load("config.ini")
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
serverPort := cfg.Section("server").Key("port").String()
redisHost := cfg.Section("redis").Key("host").String()
redisPort := cfg.Section("redis").Key("port").String()
fmt.Printf("Server Port: %s\n", serverPort)
fmt.Printf("Redis Host: %s\n", redisHost)
fmt.Printf("Redis Port: %s\n", redisPort)
}Writing to an INI File
Now, let's see how you can write to an INI file. Suppose you want to create a new INI file with the following content:
[app]
name = MyApp
version = 1.2.3
Here is how you can achieve that:
package main
import (
"log"
"github.com/go-ini/ini"
)
func main() {
cfg := ini.Empty()
section := cfg.Section("app")
section.Key("name").SetValue("MyApp")
section.Key("version").SetValue("1.2.3")
err := cfg.SaveTo("app.ini")
if err != nil {
log.Fatalf("Failed to save file: %v", err)
}
}Updating an Existing INI File
Updating an existing INI file involves reading the file, modifying the desired keys, and then saving the changes. Here’s an example:
package main
import (
"log"
"github.com/go-ini/ini"
)
func main() {
cfg, err := ini.Load("config.ini")
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
cfg.Section("redis").Key("host").SetValue("127.0.0.1")
err = cfg.SaveTo("config.ini")
if err != nil {
log.Fatalf("Failed to save file: %v", err)
}
}This example modifies the Redis host address in the config.ini file and saves those changes back to the file.
Conclusion
The go-ini package provides a straightforward and effective method for reading and writing INI files in Go. With its concise API, it can handle various operations necessary for managing INI configuration files, making it a great tool for Go developers.