CodexBloom - Programming Q&A Platform

Parsing Nested INI Files in Go - Handling Sections with Duplicates

πŸ‘€ Views: 29 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-25
go ini parsing Go

I'm collaborating on a project where I've hit a wall trying to I'm currently working on a Go project where I need to parse a nested INI configuration file, but I'm running into issues when dealing with sections that have duplicate keys... My INI file looks something like this: ```ini [database] user = admin password = secret [server] port = 8080 [database] user = guest password = guest123 ``` The scenario I'm working with is how to handle the duplicate `[database]` sections. I would like to preserve the last occurrence of each key. I've tried using the `gopkg.in/ini.v1` package, but I noticed that it only keeps the first occurrence when I call `Load()`. Here’s what I have so far: ```go package main import ( "fmt" "gopkg.in/ini.v1" ) func main() { cfg, err := ini.Load("config.ini") if err != nil { fmt.Println("behavior loading INI file:", err) return } // This prints only the first occurrence of 'user' in [database] fmt.Println(cfg.Section("database").Key("user").String()) } ``` My goal is to retrieve a map or slice that includes both users from the duplicate sections. I've considered parsing the file manually, but I'd prefer to use a library if possible. Is there a way to override the default behavior of the `ini` package to get the last values, or is there a better library for this type of INI parsing? Any guidance on best practices for handling INI files in Go would be much appreciated. I'm working in a Windows 11 environment.