Problem: Construct a bash script from a Golang program that iterates over a list of dependencies, checks their types, and prints customized commands based on those types using switch-case statements.
Answer:
The following updated Golang code accomplishes the desired behavior:
<code class="go">package main 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 } 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}}" {{switch .Type}} case "runner1": echo "Submitting api1" case "runner2": echo "Submitting api2" default: echo "Unknown type" {{end}} {{end}} ` tt := template.Must(template.New("").Parse(t)) err = tt.Execute(os.Stdout, f) if err != nil { log.Println("executing template:", err) } }</code>
Explanation:
Result:
The example bash script produced by this code is:
<code class="bash">#!/bin/bash echo "type is runner" Submitting api1 echo "type is runner2" Submitting api2</code>
Additional Considerations:
The above is the detailed content of How to Generate a Customized Bash Script Using Go Templates, Switch-Case Statements, and YAML Data?. For more information, please follow other related articles on the PHP Chinese website!