搜尋
首頁後端開發Golang編輯時在 YAML 檔案中保留單引號

编辑时在 YAML 文件中保留单引号

php小編香蕉介紹:在進行編輯時,保留單引號是一個重要的技巧。在YAML檔案中,使用單引號可以確保文字內容被原樣保留,不會受到解析器的解釋。這種方式可以避免特殊字元或特定格式的資料出現錯誤,確保文件內容的準確性和完整性。無論是處理設定檔還是編寫程式碼,保留單引號都是一個很好的習慣,能夠幫助我們更好地管理和維護程式碼。

問題內容

我想編輯 YAML 檔案中某些鍵的值,同時保持其餘鍵不變。我編寫了一個片段來為這些鍵插入一些值,但生成的新檔案不維護單引號 (')。如何避免這種情況?

我的程式碼:

<code>func updateVariables(nameValue, nameCluster string) error {
    
    yamlFile, err := os.ReadFile("path")
    if err != nil {
        return fmt.Errorf("Error reading YAML file: %v", err)
    }

    var config PipelineConfig

    err = yaml.Unmarshal(yamlFile, &config)
    if err != nil {
        return fmt.Errorf("Error parsing YAML file: %v", err)
    }

    for i := range config.Variables {
        switch config.Variables[i].Name {
        case "app_name":
            config.Variables[i].Value = nameValue
        case "cluster_name":
            config.Variables[i].Value = nameCluster

        }
    }

    modifiedYAML, err := yaml.Marshal(&config,)
    if err != nil {
        return fmt.Errorf("Error converting structure to YAML: %v", err)
    }

    err = os.WriteFile("path", modifiedYAML, 0644)
    if err != nil {
        return fmt.Errorf("Error writing modified YAML file: %v", err)
    }
    fmt.Println("File YAML modified.")
    return nil
}
</code>

我的結構:

<code>type PipelineConfig struct {
    Trigger   string `yaml:"trigger"`
    Variables []struct {
        Name  string `yaml:"name"`
        Value string `yaml:"value"`
    } `yaml:"variables"`
    
    Stages []struct {
        Template   string `yaml:"template"`
        Parameters struct {
            AppName       string `yaml:"app_name"`
            AppRepoBranch string `yaml:"app_repo_branch"`
            LocationEnv   string `yaml:"location_env"`
            ComponentName string `yaml:"component_name"`
            ClusterName   string `yaml:"cluster_name"`
        } `yaml:"parameters"`
    } `yaml:"stages"`
}
</code>

編輯前歸檔 yaml

trigger: none

variables:
  - name: app_name
    value: '<name>'
  - name: cluster_name
    value: '<cluster>'
  - name: component_name
    value: '<component>'
  - name: location_env
    value: 'dev'


stages:
  - template: 'tem'
    parameters:
      app_name: '${{ variables.app_name }}'
      app_repo_branch: 'dev'
      location_env: '${{ variables.location_env }}'
      component_name: '${{ variables.component_name }}'
      cluster_name: '${{ variables.cluster_name }}'

編輯後歸檔yaml

trigger: none
variables:
    - name: app_name
      value: test
    - name: cluster_name
      value: test
    - name: component_name
      value: <component>
    - name: location_env
      value: dev

stages:
    - template: tem
      parameters:
        app_name: ${{ variables.app_name }}
        app_repo_branch: develop
        location_env: ${{ variables.location_env }}
        component_name: ${{ variables.component_name }}
        cluster_name: ${{ variables.cluster_name }}

如您所見,單引號消失了。有什麼建議嗎?

解決方法

yaml.Unmarshal 函數將yaml 值解組到不帶元資料的自訂結構(stylekind) > 等)。 yaml.Marshal 函數正在處理自訂結構,將元資料值設為預設值。要存取元資料的字段,需要使用 yaml.Node$ $endc$$

在您的情況下 Value 欄位具有 yaml.Style 等於 yaml.SingleQuotedStyle

要存取它(解組後不要遺失),請將 Value 欄位類型變更為 yaml.Node

Variables []struct {
    Name  string    `yaml:"name"`
    Value yaml.Node `yaml:"value"`
} `yaml:"variables"`
for i := range config.Variables {
    switch config.Variables[i].Name.Value {
    case "app_name":
        config.Variables[i].Value.Value = nameValue
    case "cluster_name":
        config.Variables[i].Value.Value = nameCluster
    }
}

遊樂場

以上是編輯時在 YAML 檔案中保留單引號的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
在Golang和Python之間進行選擇:適合您的項目在Golang和Python之間進行選擇:適合您的項目Apr 19, 2025 am 12:21 AM

golangisidealforperformance-Critical-clitageAppations and ConcurrentPrompromming,而毛皮刺激性,快速播種和可及性。 1)forhigh-porformanceneeds,pelectgolangduetoitsefefsefefseffifeficefsefeflicefsiveficefsiveandconcurrencyfeatures.2)fordataa-fordataa-fordata-fordata-driventriventriventriventriventrivendissp pynonnononesp

Golang:並發和行動績效Golang:並發和行動績效Apr 19, 2025 am 12:20 AM

Golang通過goroutine和channel實現高效並發:1.goroutine是輕量級線程,使用go關鍵字啟動;2.channel用於goroutine間安全通信,避免競態條件;3.使用示例展示了基本和高級用法;4.常見錯誤包括死鎖和數據競爭,可用gorun-race檢測;5.性能優化建議減少channel使用,合理設置goroutine數量,使用sync.Pool管理內存。

Golang vs. Python:您應該學到哪種語言?Golang vs. Python:您應該學到哪種語言?Apr 19, 2025 am 12:20 AM

Golang更適合系統編程和高並發應用,Python更適合數據科學和快速開發。 1)Golang由Google開發,靜態類型,強調簡潔性和高效性,適合高並發場景。 2)Python由GuidovanRossum創造,動態類型,語法簡潔,應用廣泛,適合初學者和數據處理。

Golang vs. Python:性能和可伸縮性Golang vs. Python:性能和可伸縮性Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang vs.其他語言:比較Golang vs.其他語言:比較Apr 19, 2025 am 12:11 AM

Go語言在並發編程、性能、學習曲線等方面有獨特優勢:1.並發編程通過goroutine和channel實現,輕量高效。 2.編譯速度快,運行性能接近C語言。 3.語法簡潔,學習曲線平緩,生態系統豐富。

Golang和Python:了解差異Golang和Python:了解差異Apr 18, 2025 am 12:21 AM

Golang和Python的主要區別在於並發模型、類型系統、性能和執行速度。 1.Golang使用CSP模型,適用於高並發任務;Python依賴多線程和GIL,適合I/O密集型任務。 2.Golang是靜態類型,Python是動態類型。 3.Golang編譯型語言執行速度快,Python解釋型語言開發速度快。

Golang vs.C:評估速度差Golang vs.C:評估速度差Apr 18, 2025 am 12:20 AM

Golang通常比C 慢,但Golang在並發編程和開發效率上更具優勢:1)Golang的垃圾回收和並發模型使其在高並發場景下表現出色;2)C 通過手動內存管理和硬件優化獲得更高性能,但開發複雜度較高。

Golang:雲計算和DevOps的關鍵語言Golang:雲計算和DevOps的關鍵語言Apr 18, 2025 am 12:18 AM

Golang在雲計算和DevOps中的應用廣泛,其優勢在於簡單性、高效性和並發編程能力。 1)在雲計算中,Golang通過goroutine和channel機制高效處理並發請求。 2)在DevOps中,Golang的快速編譯和跨平台特性使其成為自動化工具的首選。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境