我正在使用以下代码来解析yaml并应将输出作为runners对象,并且该函数build应更改数据结构并根据以下结构提供输出
runners
build
type Exec struct { NameVal string Executer []string }
这是我尝试过的方法,但是我不确定如何从yaml中获取的值 替换 函数运行器中 的硬代码值
return []Exec{ {"#mytest", []string{"spawn child process", "build", "gulp"}}, }
与来自 parsed runner
parsed runner
这就是我尝试过的所有想法,该怎么做?
package main import ( "log" "gopkg.in/yaml.v2" ) var runContent = []byte(` api_ver: 1 runners: - name: function1 data: mytest type: - command: spawn child process - command: build - command: gulp - name: function2 data: mytest2 type: - command: webpack - name: function3 data: mytest3 type: - command: ruby build - name: function4 type: - command: go build `) type Result struct { Version string `yaml:"api_ver"` Runners []Runners `yaml:"runners"` } type Runners struct { Name string `yaml:"name"` Type []Command `yaml:"type"` } type Command struct { Command string `yaml:"command"` } func main() { var runners Result err := yaml.Unmarshal(runContent, &runners) if err != nil { log.Fatalf("Error : %v", err) } //Here Im calling to the function with the parsed structured data which need to return the list of Exec build("function1", runners) } type Exec struct { NameVal string Executer []string } func build(name string, runners Result) []Exec { for _, runner := range runners.Runners { if name == runner.Name { return []Exec{ // this just for example, nameVal and Command {"# mytest", []string{"spawn child process", "build", "gulp"}}, } } } }
将runners对象的名称分配给名称的struct Exec字段,并[]string使用与名称匹配的函数命令将命令列表附加到type字段:
Exec
[]string
func build(name string, runners Result) []Exec { exec := make([]Exec, len(runners.Runners)) for i, runner := range runners.Runners { if name == runner.Name { exec[i].NameVal = runner.Name for _, cmd := range runner.Type { exec[i].Executer = append(exec[i].Executer, cmd.Command) } fmt.Printf("%+v", exec) return exec } } return exec }
操场上的工作代码