关于yaml:使用yamlv2操作yaml文件

37次阅读

共计 1207 个字符,预计需要花费 4 分钟才能阅读完成。

1. 装置 yaml.v2

go get gopkg.in/yaml.v2

2. 复制 yaml 文件到另外一个文件

config/prometheus.yml

global:
  scrape_interval:     15s
  evaluation_interval: 15s

alerting:
  alertmanagers:
  - static_configs:
    - targets:
       - "localhost:9093"

rule_files:
   - "rules/*.yml"
scrape_configs:
  - job_name: 'prometheus'

    static_configs:
    - targets: ['localhost:9090']
  - job_name: 'node'
    basic_auth:
      username: prometheus
      password: 123456
    static_configs:
    - targets: ['localhost:9100']

程序

package main

type PrometheusConfig struct{Global interface{} `yaml:"global"`                 // 具体节点能够具体定义,此处都有空接口进行定义
    Alerting interface{} `yaml:"alerting"`
    RuleRiles []string `yaml:"rule_files"`
    ScrapeConfigs []interface{} `yaml:"scrape_configs"`
}

func main(){f,err := os.Open("config/prometheus.yml")
    if err != nil {log.Fatal("open file err;",err)
    }
    defer f.Close()
    dec := yaml.NewDecoder(f)
    var prometheusConfig PrometheusConfig
    err = dec.Decode(&prometheusConfig)
    if err != nil {log.Fatal("transfer prometheus config err:",err)
    }
    log.Printf("prometheus config:%s \n",prometheusConfig)
    premetheusV2, err := os.Create("config/prometheus2.yml")
    if err != nil {log.Fatal("create premetheusV2 err:",err)
    }
    defer premetheusV2.Close()
    encoder := yaml.NewEncoder(premetheusV2)
    err = encoder.Encode(prometheusConfig)
    if err != nil {log.Fatal("save prometheus err:",err)
    }

}

3. 应用例子

官网文档 https://pkg.go.dev/gopkg.in/y…

正文完
 0