Name Mapper

To save your time and make your code cleaner, this library supports NameMapper between struct field and actual section and key name.

There are 2 built-in name mappers:

  • AllCapsUnderscore: it converts to format ALL_CAPS_UNDERSCORE then match section or key.
  • TitleUnderscore: it converts to format title_underscore then match section or key.
    To use them:
  1. type Info struct {
  2. PackageName string
  3. }
  4. func main() {
  5. err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini"))
  6. // ...
  7. cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
  8. // ...
  9. info := new(Info)
  10. cfg.NameMapper = ini.AllCapsUnderscore
  11. err = cfg.MapTo(info)
  12. // ...
  13. }

Same rules of name mapper apply to ini.ReflectFromWithMapper function.

Value Mapper

To expand values (e.g. from environment variables), you can use the ValueMapper to transform values:

  1. type Env struct {
  2. Foo string `ini:"foo"`
  3. }
  4. func main() {
  5. cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n")
  6. cfg.ValueMapper = os.ExpandEnv
  7. // ...
  8. env := &Env{}
  9. err = cfg.Section("env").MapTo(env)
  10. }

This would set the value of env.Foo to the value of the environment variable MY_VAR.

原文: https://ini.unknwon.io/docs/advanced/name_and_value_mapper