package main import ( "bytes" "fmt" "code.uint32.ru/tiny/conf" ) var testConf = []byte(` # commented port=10000 servers = 10.0.0.1, 10.0.0.2, 10.0.0.3 some_ints = 1, 2, 3, 4 map = a: 1, b: 2, c:3 `) func main() { r := bytes.NewReader(testConf) // creating io.Reader from []byte() config, _ := conf.Read(r) // we could call conf.Open("filename") here // main methods if conf.Map are Find, Get, and GetDefault // Find returns conf.Value and a bool indicating whether value has been found _, ok := config.Find("port") if !ok { // key "port" was not found panic("not found") } // GetDefault will return Value set to provided default // if value is not in the map. In this example the returned // value wiill be Value("vyvalue"). def := config.GetDefault("non-existant-key", "myvalue") fmt.Println(def.String()) // "myvalue" // Get will return empty conf.Value if it was not found. // get values from line "servers = 10.0.0.1, 10.0.0.2, 10.0.0.3". servers := config.Get("servers") // the returned Value has many methods to convert the underlying string for i, s := range servers.StringSlice() { fmt.Println(i+1, "\t", s) // 10.0.0.1 10.0.0.2 10.0.0.3 } // We can cast Setting.Value to a desired type including int, float64, // bool and string. Method will return an error if Setting Value field // can not be interpreted as desired type. n, err := config.Get("port").Int() if err != nil { // n is zero value for int and we failed to convert // value from our file to int. panic(err) } fmt.Println(n) // 10000 // The value methods are as follows: v := config.Get("some_ints") // the config line is "some_ints = 1, 2, 3, 4" // String returns string as is (only trimmed from whitespace) s := v.String() fmt.Printf("%T, %v\n", s, s) // string, 1, 2, 3, 4 // StringSlice tries to interpret value as comma-separated list, trims each element from whitespace ss := v.StringSlice() fmt.Printf("%T, %v\n", ss, ss) // []string, [1 2 3 4] // IntSlice parses value in the same way as StringSlice then tries to convert each element // to int. Failure to convert any element is an error. is, err := v.IntSlice() if err != nil { panic(err) } fmt.Printf("%T, %v\n", is, is) // []int, [1 2 3 4] // there are similar methods for bool and float64 types. // Map method of Value tries to interpret value as mapping where // keys are sepearated from values with ":". // This example parses line for the example config // "map = a: 1, b: 2, c: 3" m, _ := config.Get("map").Map() // return conf.Map and error if any fmt.Printf("%T, %v\n", m, m) // conf.Map, map[a:1 b:2 c:3] // key "a" can be interpreted as int x, _ := m.Get("c").Int() fmt.Println(x) // prints 3 }