Skip to content
derdon edited this page Mar 27, 2013 · 3 revisions

As said in the previous page, ini supports the creation of custom formatters. A formatter is a function which gets called directly after a property's value from a section has been fetched. It receives the value it got as a parameter and must return an interface{} value and a value of type error. This is useful if you have values in a config file written in a special form. The following example formats values from the property "fruits" with the formatter function parseCommaSeperatedList. The formatter simply splits the value by comma and removes leading and trailing whitespace. The output of the program is values: []string{"apples", "bananas", "pears"}.

package main

import (
	"fmt"
	"strings"
)

import "github.com/derdon/ini"

func parseCommaSeperatedList(s string) (interface{}, error) {
	values := []string{}
	for _, value := range strings.Split(s, ",") {
		values = append(values, strings.TrimSpace(value))
	}
	return values, nil
}

func main() {
	filecontent := `[section]
fruits = apples, bananas, pears`
	conf, err := ini.NewConfigFromString(filecontent)
	if err != nil {
		panic(err)
	}
	values, err := conf.GetFormatted("section", "fruits", parseCommaSeperatedList)
	if err != nil {
		panic(err)
	}
	fmt.Printf("values: %#v\n", values)
}
Clone this wiki locally