Home >Backend Development >Golang >How to Use Go Template with Switch and ForEach to Generate Bash Scripts with Dependency Type Specific Commands?
Golang Template with Switch & ForEach
Background:
The task is to generate a bash.sh file from a Go program that incorporates both switch and ForEach constructs. The generated script should iterate through a list of dependencies, accessing their types and using the types to print specific messages.
Problem:
An initial attempt using YAML marshaling and template parsing resulted in incorrect functionality. The issue arose because the dependency type was not correctly used in the template.
Solution:
To resolve the problem, the dependency structure was modified to include an Install field representing the commands to be executed for each type. A template was then created to iterate over the Dependency array and print the commands based on the type using range and switch constructs.
The following code snippet illustrates the revised approach:
<code class="go">import ( "log" "text/template" "gopkg.in/yaml.v2" "os" ) type File struct { TypeVersion string `yaml:"_type-version"` Dependency []Dependency } type Dependency struct { Name string Type string CWD string Install map[string]string } var data = ` _type-version: "1.0.0" dependency: - name: ui type: runner cwd: /ui install: api: echo api1 - name: ui2 type: runner2 cwd: /ui2 install: api: echo api2 ` func main() { f := File{} err := yaml.Unmarshal([]byte(data), &f) if err != nil { log.Fatalf("error: %v", err) } const t = ` #!/bin/bash {{range .Dependency}} echo "type is {{.Type}}" echo "cwd is {{.CWD}}" {{range $installName, $installCmd := .Install}} echo "install {{$installName}} ({{$installCmd}})" {{end}} {{end}} ` tt := template.Must(template.New("").Parse(t)) err = tt.Execute(os.Stdout, f) if err != nil { log.Println("executing template:", err) } }</code>
Output:
The updated code generates the expected script:
<code class="sh">#!/bin/bash echo "type is runner" echo "cwd is /ui" echo "install api (echo api1)" echo "type is runner2" echo "cwd is /ui2" echo "install api (echo api2)"</code>
In summary, the solution involves correctly using the template to access the dependency data and generate the appropriate commands based on the type using switch and ForEach.
The above is the detailed content of How to Use Go Template with Switch and ForEach to Generate Bash Scripts with Dependency Type Specific Commands?. For more information, please follow other related articles on the PHP Chinese website!