github.com/hashicorp/hcl/v2@v2.20.0/hclsimple/hclsimple_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package hclsimple_test 5 6 import ( 7 "fmt" 8 "log" 9 "reflect" 10 "testing" 11 12 "github.com/hashicorp/hcl/v2/hclsimple" 13 ) 14 15 func Example_nativeSyntax() { 16 type Config struct { 17 Foo string `hcl:"foo"` 18 Baz string `hcl:"baz"` 19 } 20 21 const exampleConfig = ` 22 foo = "bar" 23 baz = "boop" 24 ` 25 26 var config Config 27 err := hclsimple.Decode( 28 "example.hcl", []byte(exampleConfig), 29 nil, &config, 30 ) 31 if err != nil { 32 log.Fatalf("Failed to load configuration: %s", err) 33 } 34 fmt.Printf("Configuration is %v\n", config) 35 36 // Output: 37 // Configuration is {bar boop} 38 } 39 40 func Example_jsonSyntax() { 41 type Config struct { 42 Foo string `hcl:"foo"` 43 Baz string `hcl:"baz"` 44 } 45 46 const exampleConfig = ` 47 { 48 "foo": "bar", 49 "baz": "boop" 50 } 51 ` 52 53 var config Config 54 err := hclsimple.Decode( 55 "example.json", []byte(exampleConfig), 56 nil, &config, 57 ) 58 if err != nil { 59 log.Fatalf("Failed to load configuration: %s", err) 60 } 61 fmt.Printf("Configuration is %v\n", config) 62 63 // Output: 64 // Configuration is {bar boop} 65 } 66 67 func TestDecodeFile(t *testing.T) { 68 type Config struct { 69 Foo string `hcl:"foo"` 70 Baz string `hcl:"baz"` 71 } 72 73 var got Config 74 err := hclsimple.DecodeFile("testdata/test.hcl", nil, &got) 75 if err != nil { 76 t.Fatalf("unexpected error(s): %s", err) 77 } 78 want := Config{ 79 Foo: "bar", 80 Baz: "boop", 81 } 82 if !reflect.DeepEqual(got, want) { 83 t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, want) 84 } 85 }