github.com/hashicorp/hcl/v2@v2.20.0/gohcl/encode_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package gohcl_test
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/hashicorp/hcl/v2/gohcl"
    10  	"github.com/hashicorp/hcl/v2/hclwrite"
    11  )
    12  
    13  func ExampleEncodeIntoBody() {
    14  	type Service struct {
    15  		Name string   `hcl:"name,label"`
    16  		Exe  []string `hcl:"executable"`
    17  	}
    18  	type Constraints struct {
    19  		OS   string `hcl:"os"`
    20  		Arch string `hcl:"arch"`
    21  	}
    22  	type App struct {
    23  		Name        string       `hcl:"name"`
    24  		Desc        string       `hcl:"description"`
    25  		Constraints *Constraints `hcl:"constraints,block"`
    26  		Services    []Service    `hcl:"service,block"`
    27  	}
    28  
    29  	app := App{
    30  		Name: "awesome-app",
    31  		Desc: "Such an awesome application",
    32  		Constraints: &Constraints{
    33  			OS:   "linux",
    34  			Arch: "amd64",
    35  		},
    36  		Services: []Service{
    37  			{
    38  				Name: "web",
    39  				Exe:  []string{"./web", "--listen=:8080"},
    40  			},
    41  			{
    42  				Name: "worker",
    43  				Exe:  []string{"./worker"},
    44  			},
    45  		},
    46  	}
    47  
    48  	f := hclwrite.NewEmptyFile()
    49  	gohcl.EncodeIntoBody(&app, f.Body())
    50  	fmt.Printf("%s", f.Bytes())
    51  
    52  	// Output:
    53  	// name        = "awesome-app"
    54  	// description = "Such an awesome application"
    55  	//
    56  	// constraints {
    57  	//   os   = "linux"
    58  	//   arch = "amd64"
    59  	// }
    60  	//
    61  	// service "web" {
    62  	//   executable = ["./web", "--listen=:8080"]
    63  	// }
    64  	// service "worker" {
    65  	//   executable = ["./worker"]
    66  	// }
    67  }