diff options
| author | Shulhan <ms@kilabit.info> | 2019-06-02 10:14:23 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2019-06-02 10:14:23 +0700 |
| commit | c335a55f3017de4a82b59c8305268c1a69653f82 (patch) | |
| tree | 558a2a0a6956979b127832bbe016e6b7d4492dbd | |
| parent | 3fe8a7ec4f8bb9a0ddbd941eb5af90cfc905b888 (diff) | |
| download | pakakeh.go-c335a55f3017de4a82b59c8305268c1a69653f82.tar.xz | |
ini: add method Vars that return all variables as map
Given a section name and/or subsection name, Vars() method will return
all variables as map of key and value.
If there is a duplicate in key's name, only the last key value that will
be store on map value.
This method is a shortcut that can be used in templating.
| -rw-r--r-- | lib/ini/ini.go | 27 | ||||
| -rw-r--r-- | lib/ini/ini_example_test.go | 39 |
2 files changed, 66 insertions, 0 deletions
diff --git a/lib/ini/ini.go b/lib/ini/ini.go index 0ff3c1fa..d282337b 100644 --- a/lib/ini/ini.go +++ b/lib/ini/ini.go @@ -436,6 +436,33 @@ func (in *Ini) Vals(keyPath string) (vals []string) { } // +// Vars return all variables in section and/or subsection as map of string. +// If there is a duplicate in key's name, only the last key value that will be +// store on map value. +// +// This method is a shortcut that can be used in templating. +// +func (in *Ini) Vars(sectionPath string) (vars map[string]string) { + names := strings.Split(sectionPath, ":") + switch len(names) { + case 0: + return + case 1: + names = append(names, "") + } + + asmap := in.AsMap(names[0], names[1]) + if len(asmap) > 0 { + vars = make(map[string]string, len(asmap)) + } + for k, v := range asmap { + vars[k] = v[len(v)-1] + } + + return +} + +// // Write the current parsed Ini into writer `w`. // func (in *Ini) Write(w io.Writer) (err error) { diff --git a/lib/ini/ini_example_test.go b/lib/ini/ini_example_test.go index cf1e1c9c..3ee93851 100644 --- a/lib/ini/ini_example_test.go +++ b/lib/ini/ini_example_test.go @@ -408,3 +408,42 @@ key=value3 // [] // [value1 value2 value3] } + +func ExampleIni_Vars() { + input := ` +[section] +key=value1 +key2= + +[section "sub"] +key=value1 +key=value2 + +[section] +key=value2 +key2=false + +[section "sub"] +key=value2 +key=value3 +` + + ini, err := Parse([]byte(input)) + if err != nil { + log.Fatal(err) + } + + for k, v := range ini.Vars("section:") { + fmt.Println(k, "=", v) + } + + fmt.Println() + for k, v := range ini.Vars("section:sub") { + fmt.Println(k, "=", v) + } + // Unordered output: + // section::key = value2 + // section::key2 = false + // + // key = value3 +} |
