Load from data sources

As advertised, load from different data sources is possible and effortless.

So, what is a Data Source anyway?

A Data Source is either raw data in type []byte, a file name with type string or io.ReadCloser. You can load as many data sources as you want. Passing other types will simply return an error.

  1. cfg, err := ini.Load(
  2. []byte("raw data"), // Raw data
  3. "filename", // File
  4. ioutil.NopCloser(bytes.NewReader([]byte("some other data"))),
  5. )

Or start with an empty object:

  1. cfg := ini.Empty()

When you cannot decide how many data sources to load at the beginning, you will still be able to Append() them later.

  1. err := cfg.Append("other file", []byte("other raw data"))

If you have a list of files with possibilities that some of them may not available at the time, and you don’t know exactly which ones, you can use LooseLoad() to ignore nonexistent files without returning error.

  1. cfg, err := ini.LooseLoad("filename", "filename_404")

The cool thing is, whenever the file is available to load while you’re calling Reload() method, it will be counted as usual.

Data Overwrite

One minor thing you need to keep in mind before you go. Data overwrite will happen when you load from more than one data sources. The value with same key name in the later data source will overwrite whatever previously read.

For example, if you load two files my.ini and my.ini.local (example input and output from Getting Started), value of app_mode will be production not development.

  1. cfg, err := ini.Load("my.ini", "my.ini.local")
  2. ...
  3. cfg.Section("").Key("app_mode").String() // production

The only exception to data overwrite rule is when you use ShadowLoad.

Save your configuration

Finally, it’s time to save your configuration to somewhere.

A typical way to save configuration is writing it to a file:

  1. // ...
  2. err = cfg.SaveTo("my.ini")
  3. err = cfg.SaveToIndent("my.ini", "\t")

Another way to save is writing to a io.Writer interface:

  1. // ...
  2. cfg.WriteTo(writer)
  3. cfg.WriteToIndent(writer, "\t")

By default, spaces are used to align “=” sign between key and values, to disable that:

  1. ini.PrettyFormat = false

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