我想知道这种逻辑在Golang是否可行.我有一个yaml文件:

initSteps:
  - "pip install --upgrade pip"
  - "python3 --version"

buildSteps:
  - "pip install ."

runProcess:
  - "python3 test.py"

我用gopkg.in/yaml.v3来迭代这些步骤.我在下面有一个函数,它将指令放入如下 map 中:


func init() {

    // add map from yaml to steps
    f, err := ioutil.ReadFile(devrun)

    if err != nil {
        panic(err)
    }
    steps = make(map[interface{}]interface{})

    err2 := yaml.Unmarshal(f, &steps)

    if err2 != nil {
        panic(err2)
    }
}

在my main函数中,如果键匹配,则使用此函数迭代值:

    for k, v := range steps {
        if k == "initSteps" {
            s := reflect.ValueOf(v)
            for i := 0; i < s.Len(); i++ {
                singleVertex := s.Index(i).Elem()
                fmt.Println(singleVertex)
            }
        }
    }

我想看看是否有可能从steps开始迭代该键,以及如何将其添加到中.如果k.initSteps,我可以这样做:yaml文件中的键总是相同的,唯一改变的是它们下面的步骤.

推荐答案

你可以阅读你的.带有viper的yaml配置文件.简单代码示例:

import (
    "fmt"
    "github.com/spf13/viper"
)

func main() {
    readYaml()
}

func readYaml() {
    viper.SetConfigName("test")                // name of config file (without extension)
    viper.SetConfigType("yaml")                // REQUIRED if the config file does not have the extension in the name
    viper.AddConfigPath("./Examples/readyaml") // path to look for the config file in

    err := viper.ReadInConfig() // Find and read the config file
    if err != nil {             // Handle errors reading the config file
        panic(fmt.Errorf("fatal error config file: %w", err))
    }
    fmt.Println(viper.AllKeys())
    for _, i := range viper.AllKeys() {
        fmt.Println(i, viper.Get(i))
    }

}

输出:

[initsteps buildsteps runprocess]

initsteps [pip install --upgrade pip python3 --version]

buildsteps [pip install .]

runprocess [python3 test.py]

Go相关问答推荐

Makefile:现有文件上没有这样的文件或目录,不加载环境变量

如何存储来自异步Goroutine的返回值列表?

MaybeReadByte对通道的使用如何在Go中提供随机行为?

GO:如何指定类型约束,使S方法的参数类型与接收方的参数类型相同

从文件读取字节,将其保存到 struct 体并修改值

Json.Unmarshal() 和 gin.BindJson() 之间的区别

htmx 表单 + gin 无法正确读取请求正文

用接口来模拟amqp091go的困难

如何解决我的 Go 聊天应用程序中 cookie 未在本地主机端口之间传输的问题?

xml.Unmarshal 不支持的类型 struct

设置 graphql 的最大文件上传大小(golang)

创建新对象后如何返回嵌套实体?

如何使用 go-playground/validator 编写 snake case 绑定标签?

如何将多个切片打印为一个切片?

Go:用于 XML 解码的嵌套 struct 中的提升字段

在 Go 中将十六进制转换为带符号的 Int

什么是无效字符实体 &ccb

try 执行`go test ./... -v`时,Golang中有没有办法设置标志

有没有办法在golang中映射一组对象?

Go http标准库中的内存泄漏?