golang yml写入
config.yml
app: host: 127.0.0.1 port: 3306 username: adminsdsd password: admin log: suffix: log maxSize: 5
main.go 先读取再写入
package main import ( "fmt" "io/ioutil" "log" "os" "github.com/go-yaml/yaml" ) type Config struct { App *App `yaml:"app"` Log *Log `yaml:"log"` } type App struct { Host string `yaml:"host"` Port int `yaml:"port"` Username string `yaml:"username"` Password string `yaml:"password"` } type Log struct { Suffix string `yaml:"suffix"` MaxSize int `yaml:"maxSize"` } func InitConfig() { yamlFile, err := ioutil.ReadFile("./config/config.yml") if err != nil { fmt.Println(err.Error()) } var _config *Config err = yaml.Unmarshal(yamlFile, &_config) if err != nil { fmt.Println(err.Error()) } fmt.Printf("config.app: %#v\n", _config.App) fmt.Printf("config.log: %#v\n", _config.Log) // 写入test.yml file, err := os.OpenFile("test.yml", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Fatalf("error opening/creating file: %v", err) } defer file.Close() enc := yaml.NewEncoder(file) _config.App.Host = "xasas" _config.App.Password = "xasas" err = enc.Encode(Config{ App: _config.App, Log: _config.Log, }) if err != nil { log.Fatalf("error encoding: %v", err) } } func main() { InitConfig() }