1// code examples for godoc 2 3package toml 4 5import ( 6 "fmt" 7) 8 9func ExampleNodeFilterFn_filterExample() { 10 tree, _ := Load(` 11 [struct_one] 12 foo = "foo" 13 bar = "bar" 14 15 [struct_two] 16 baz = "baz" 17 gorf = "gorf" 18 `) 19 20 // create a query that references a user-defined-filter 21 query, _ := CompileQuery("$[?(bazOnly)]") 22 23 // define the filter, and assign it to the query 24 query.SetFilter("bazOnly", func(node interface{}) bool { 25 if tree, ok := node.(*TomlTree); ok { 26 return tree.Has("baz") 27 } 28 return false // reject all other node types 29 }) 30 31 // results contain only the 'struct_two' TomlTree 32 query.Execute(tree) 33} 34 35func ExampleQuery_queryExample() { 36 config, _ := Load(` 37 [[book]] 38 title = "The Stand" 39 author = "Stephen King" 40 [[book]] 41 title = "For Whom the Bell Tolls" 42 author = "Ernest Hemmingway" 43 [[book]] 44 title = "Neuromancer" 45 author = "William Gibson" 46 `) 47 48 // find and print all the authors in the document 49 authors, _ := config.Query("$.book.author") 50 for _, name := range authors.Values() { 51 fmt.Println(name) 52 } 53} 54 55func Example_comprehensiveExample() { 56 config, err := LoadFile("config.toml") 57 58 if err != nil { 59 fmt.Println("Error ", err.Error()) 60 } else { 61 // retrieve data directly 62 user := config.Get("postgres.user").(string) 63 password := config.Get("postgres.password").(string) 64 65 // or using an intermediate object 66 configTree := config.Get("postgres").(*TomlTree) 67 user = configTree.Get("user").(string) 68 password = configTree.Get("password").(string) 69 fmt.Println("User is ", user, ". Password is ", password) 70 71 // show where elements are in the file 72 fmt.Printf("User position: %v\n", configTree.GetPosition("user")) 73 fmt.Printf("Password position: %v\n", configTree.GetPosition("password")) 74 75 // use a query to gather elements without walking the tree 76 results, _ := config.Query("$..[user,password]") 77 for ii, item := range results.Values() { 78 fmt.Printf("Query result %d: %v\n", ii, item) 79 } 80 } 81} 82