1b9738a196
These are wrappers around the lower-level hclwrite package that are able to reverse a subset of the behavior of the Decode functions to populate an hclwrite DOM. They are not fully symmetrical with DecodeBody because that function can leave certain parts of the configuration in its opaque form for later decoding, and these encode functions don't have enough information to repack that abstract/opaque form into new source code. In practice we expect that callers using complex techniques like partial decoding will also use more complex techniques with the hclwrite API directly, since they will need to coordinate partial _encoding_ of data that has been portioned off into separate structures, which gohcl is not equipped to do itself.
65 lines
1.2 KiB
Go
65 lines
1.2 KiB
Go
package gohcl_test
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/hashicorp/hcl2/gohcl"
|
|
"github.com/hashicorp/hcl2/hclwrite"
|
|
)
|
|
|
|
func ExampleEncodeIntoBody() {
|
|
type Service struct {
|
|
Name string `hcl:"name,label"`
|
|
Exe []string `hcl:"executable"`
|
|
}
|
|
type Constraints struct {
|
|
OS string `hcl:"os"`
|
|
Arch string `hcl:"arch"`
|
|
}
|
|
type App struct {
|
|
Name string `hcl:"name"`
|
|
Desc string `hcl:"description"`
|
|
Constraints *Constraints `hcl:"constraints,block"`
|
|
Services []Service `hcl:"service,block"`
|
|
}
|
|
|
|
app := App{
|
|
Name: "awesome-app",
|
|
Desc: "Such an awesome application",
|
|
Constraints: &Constraints{
|
|
OS: "linux",
|
|
Arch: "amd64",
|
|
},
|
|
Services: []Service{
|
|
{
|
|
Name: "web",
|
|
Exe: []string{"./web", "--listen=:8080"},
|
|
},
|
|
{
|
|
Name: "worker",
|
|
Exe: []string{"./worker"},
|
|
},
|
|
},
|
|
}
|
|
|
|
f := hclwrite.NewEmptyFile()
|
|
gohcl.EncodeIntoBody(&app, f.Body())
|
|
fmt.Printf("%s", f.Bytes())
|
|
|
|
// Output:
|
|
// name = "awesome-app"
|
|
// description = "Such an awesome application"
|
|
//
|
|
// constraints {
|
|
// os = "linux"
|
|
// arch = "amd64"
|
|
// }
|
|
//
|
|
// service "web" {
|
|
// executable = ["./web", "--listen=:8080"]
|
|
// }
|
|
// service "worker" {
|
|
// executable = ["./worker"]
|
|
// }
|
|
}
|