|
| 1 | +package main |
| 2 | + |
| 3 | +import "gopkg.in/ini.v1" |
| 4 | + |
| 5 | +func main() { |
| 6 | + if err := run(); err != nil { |
| 7 | + panic(err) |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +func run() error { |
| 12 | + // |
| 13 | + // 空のiniファイルを用意 |
| 14 | + // |
| 15 | + cfg := ini.Empty() |
| 16 | + |
| 17 | + // |
| 18 | + // セクションの追加 |
| 19 | + // |
| 20 | + var ( |
| 21 | + secGeneral *ini.Section |
| 22 | + secDatabase *ini.Section |
| 23 | + secLogger *ini.Section |
| 24 | + ) |
| 25 | + |
| 26 | + secGeneral = cfg.Section("General") |
| 27 | + secDatabase = cfg.Section("Database") |
| 28 | + secLogger = cfg.Section("Logging") |
| 29 | + |
| 30 | + // |
| 31 | + // キーと値の追加 |
| 32 | + // |
| 33 | + secGeneral.NewKey("AppName", "MyApplication") |
| 34 | + secGeneral.NewKey("Version", "1.0.0") |
| 35 | + secGeneral.NewKey("License", "MIT") |
| 36 | + |
| 37 | + secDatabase.NewKey("Host", "localhost") |
| 38 | + secDatabase.NewKey("User", "root") |
| 39 | + secDatabase.NewKey("Password", "") |
| 40 | + secDatabase.NewKey("DatabaseName", "my_database") |
| 41 | + |
| 42 | + secLogger.NewKey("Level", "DEBUG") |
| 43 | + key, _ := secLogger.NewKey("LogFile", "/var/log/myapp.log") |
| 44 | + key.Comment = "ログファイル" |
| 45 | + |
| 46 | + // |
| 47 | + // 書き出し |
| 48 | + // |
| 49 | + if err := cfg.SaveTo("config.ini"); err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + |
| 53 | + return nil |
| 54 | + |
| 55 | + /* |
| 56 | + $ task |
| 57 | + task: [default] go run main.go |
| 58 | + task: [default] cat config.ini |
| 59 | + [General] |
| 60 | + AppName = MyApplication |
| 61 | + Version = 1.0.0 |
| 62 | + License = MIT |
| 63 | +
|
| 64 | + [Database] |
| 65 | + Host = localhost |
| 66 | + User = root |
| 67 | + Password = |
| 68 | + DatabaseName = my_database |
| 69 | +
|
| 70 | + [Logging] |
| 71 | + Level = DEBUG |
| 72 | + ; ログファイル |
| 73 | + LogFile = /var/log/myapp.log |
| 74 | + */ |
| 75 | +} |
0 commit comments