亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GoLang 遍歷 yaml 文件

GoLang 遍歷 yaml 文件

Go
開心每一天1111 2022-12-26 16:48:48
我想知道這種邏輯在 Golang 中是否可行。我有一個這樣的 yaml 文件:initSteps:  - "pip install --upgrade pip"  - "python3 --version"buildSteps:  - "pip install ."runProcess:  - "python3 test.py"并且正在使用gopkg.in/yaml.v3迭代這些步驟。我在下面有一個函數,可以將指令放入這樣的地圖中: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)    }}如果鍵匹配,在我的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 文件的密鑰將始終相同,唯一改變的是步驟在他們之下。
查看完整描述

1 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

您可以使用 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]


查看完整回答
反對 回復 2022-12-26
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號