summaryrefslogtreecommitdiff
path: root/hclsimple/hclsimple_test.go
blob: 034edd5377f1b9d0b33d95d56b7149f38c7f826d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package hclsimple_test

import (
	"fmt"
	"log"
	"reflect"
	"testing"

	"github.com/hashicorp/hcl/v2/hclsimple"
)

func Example_nativeSyntax() {
	type Config struct {
		Foo string `hcl:"foo"`
		Baz string `hcl:"baz"`
	}

	const exampleConfig = `
	foo = "bar"
	baz = "boop"
	`

	var config Config
	err := hclsimple.Decode(
		"example.hcl", []byte(exampleConfig),
		nil, &config,
	)
	if err != nil {
		log.Fatalf("Failed to load configuration: %s", err)
	}
	fmt.Printf("Configuration is %v\n", config)

	// Output:
	// Configuration is {bar boop}
}

func Example_jsonSyntax() {
	type Config struct {
		Foo string `hcl:"foo"`
		Baz string `hcl:"baz"`
	}

	const exampleConfig = `
	{
		"foo": "bar",
		"baz": "boop"
	}
	`

	var config Config
	err := hclsimple.Decode(
		"example.json", []byte(exampleConfig),
		nil, &config,
	)
	if err != nil {
		log.Fatalf("Failed to load configuration: %s", err)
	}
	fmt.Printf("Configuration is %v\n", config)

	// Output:
	// Configuration is {bar boop}
}

func TestDecodeFile(t *testing.T) {
	type Config struct {
		Foo string `hcl:"foo"`
		Baz string `hcl:"baz"`
	}

	var got Config
	err := hclsimple.DecodeFile("testdata/test.hcl", nil, &got)
	if err != nil {
		t.Fatalf("unexpected error(s): %s", err)
	}
	want := Config{
		Foo: "bar",
		Baz: "boop",
	}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("wrong result\ngot:  %#v\nwant: %#v", got, want)
	}
}