Working with sections

To get a section, you would need to:

  1. sec, err := cfg.GetSection("section name")

For a shortcut for default section, just give an empty string as name:

  1. sec, err := cfg.GetSection("")

Alternatively, you can use ini.DEFAULT_SECTION as section name to access the default section:

  1. sec, err := cfg.GetSection(ini.DEFAULT_SECTION)

When you’re pretty sure the section exists, following code could make your life easier:

  1. sec := cfg.Section("section name")

What happens when the section somehow does not exist? Don’t panic, it automatically creates and returns a new section to you.

To create a new section:

  1. err := cfg.NewSection("new section")

To get a list of sections or section names:

  1. secs := cfg.Sections()
  2. names := cfg.SectionStrings()

Parent-child Sections

You can use . in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section.

  1. NAME = ini
  2. VERSION = v1
  3. IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
  4. [package]
  5. CLONE_URL = https://%(IMPORT_PATH)s
  6. [package.sub]
  1. cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1

Unparseable Sections

Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use LoadOptions.UnparsableSections:

  1. cfg, err := ini.LoadSources(ini.LoadOptions{
  2. UnparseableSections: []string{"COMMENTS"},
  3. }, `[COMMENTS]
  4. <1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>`)
  5. body := cfg.Section("COMMENTS").Body()
  6. /* --- start ---
  7. <1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
  8. ------ end --- */

原文: https://ini.unknwon.io/docs/howto/work_with_sections