Getting Started

We will go through a very simple example to illustrate how to get started.

First of all, create two files (my.ini and main.go) under the directory of your choice, let’s say we choose /tmp/ini.

  1. $ mkdir -p /tmp/ini
  2. $ cd /tmp/ini
  3. $ touch my.ini main.go
  4. $ tree .
  5. .
  6. ├── main.go
  7. └── my.ini
  8. 0 directories, 2 files

Now, we put some content into the my.ini file (partially take from Grafana).

  1. # possible values : production, development
  2. app_mode = development
  3. [paths]
  4. # Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
  5. data = /home/git/grafana
  6. [server]
  7. # Protocol (http or https)
  8. protocol = http
  9. # The http port to use
  10. http_port = 9999
  11. # Redirect to correct domain if host header does not match domain
  12. # Prevents DNS rebinding attacks
  13. enforce_domain = true

Great, let’s start writing some code in main.go to manipulate this file.

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

Almost there, let’s run this program and check the output.

  1. $ go run main.go
  2. App Mode: development
  3. Data Path: /home/git/grafana
  4. Server Protocol: http
  5. Email Protocol: smtp
  6. Port Number: (int) 9999
  7. Enforce Domain: (bool) true
  8. $ cat my.ini.local
  9. # possible values : production, development
  10. app_mode = production
  11. [paths]
  12. # Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
  13. data = /home/git/grafana
  14. ...

Perfect! Though the example is very basic and covered only a small bit of all functionality, but it’s a good start.

原文: https://ini.unknwon.io/docs/intro/getting_started