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()
}
复制代码

 

posted on   金科许俊  阅读(89)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具



点击右上角即可分享
微信分享提示