1 回答
TA贡献1828条经验 获得超3个赞
您提供的 yaml 包含令牌错误。在此处验证代码中使用的 yaml https://codebeautify.org/yaml-validator/cbaabb32
之后创建结构类型结果的变量而不是数组。因为您使用的 yaml 正在创建一个带有 Runners 数组和 api_version 的结构。
这
var runners []Result
应该
var runners Result
因为因为结构不是切片。获取 yaml 中使用的函数名称的命令列表。您需要遍历 runners 数组以找到函数名称并获取该函数的命令值。下面是工作代码:
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var runContent = []byte(`
api_ver: 1
runners:
- name: function1
type:
- command: spawn child process
- command: build
- command: gulp
- name: function2
type:
- command: run function 1
- name: function3
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
// parse mta yaml
err := yaml.Unmarshal(runContent, &runners)
if err != nil {
log.Fatalf("Error : %v", err)
}
commandList := getCommandList("function1", runners.Runners)
fmt.Printf("%+v", commandList)
}
func getCommandList(name string, runners []Runners) []Command {
var commandList []Command
for _, value := range runners {
if value.Name == name {
commandList = value.Type
}
}
return commandList
}
- 1 回答
- 0 关注
- 217 浏览
添加回答
举报