使用yaml.v2操作yaml文件

1.安装yaml.v2

go get gopkg.in/yaml.v2

2.复制yaml文件到另外一个文件 config/prometheus.yml
global: scrape_interval:15s evaluation_interval: 15salerting: 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 maintype 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.使用例子 【使用yaml.v2操作yaml文件】官方文档 https://pkg.go.dev/gopkg.in/y...

    推荐阅读