Go yaml
Contents
Go 读取yaml格式配置文件
package config
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v3"
)
type Service struct {
Host string `json:"host" yaml:"host"`
Port string `json:"port" yaml:"port"`
}
type MyConfig struct {
Service Service `json:"service" yaml:"service"`
}
var Config *MyConfig
func LoadConfig(filepath string) {
if filepath == "" {
return
}
// 读yaml文件
config, err := ioutil.ReadFile(filepath)
if err != nil {
fmt.Printf("read config failed, please check the path: %v , err: %v", filepath, err)
}
err = yaml.Unmarshal(config, &Config)
if err != nil {
fmt.Printf("Unmarshal to struct, err: %v", err)
}
fmt.Printf("LoadConfig: %v", Config)
}
// 写yaml文件
data, err := yaml.Marshal(SkopeoData)
if err != nil {
slog.Error("yaml marshal failed", "err", err)
return
}
err = os.WriteFile(config.AutoSyncfile, data, 0644)
if err != nil {
slog.Error("Write auto sync data to file failed", "err", err)
}