ini.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "gopkg.in/ini.v1"
  6. )
  7. func main() {
  8. ini.PrettyFormat = false
  9. cfg, err := ini.LoadSources(ini.LoadOptions{
  10. SpaceBeforeInlineComment: false,
  11. IgnoreInlineComment: true,
  12. }, "my.ini")
  13. if err != nil {
  14. fmt.Printf("Fail to read file: %v", err)
  15. os.Exit(1)
  16. }
  17. // Classic read of values, default section can be represented as empty string
  18. cfg.Section("").Comment = "#include extensions_trigger.conf"
  19. fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String())
  20. fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())
  21. // Let's do some candidate value limitation
  22. fmt.Println("Server Protocol:",
  23. cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))
  24. // Value read that is not in candidates will be discarded and fall back to given default value
  25. fmt.Println("Email Protocol:",
  26. cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))
  27. // Try out auto-type conversion
  28. fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt(9999))
  29. fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool(false))
  30. // Now, make some changes and save it
  31. cfg.Section("").Key("app_mode").SetValue("production")
  32. cfg.SaveTo("my.ini")
  33. }