【问题标题】:Generate .cfg from golang program从 golang 程序生成 .cfg
【发布时间】:2022-12-05 00:45:49
【问题描述】:

我正在开发一个需要将系统配置转储到指定路径的 Golang 项目。是否有任何库可以从 golang 程序内部生成 .cfg 文件?

我试图搜索 Viper,但找不到合适的示例来读取/写入 .cfg 文件。支持JSON、toml等格式。

【问题讨论】:

    标签: go config


    【解决方案1】:

    它不支持开箱即用的 .cfg 文件格式,但可以通过实现 Marshaler 和 Unmarshaler 接口来创建自定义配置文件类型,例如:

    package main
    
    import (
        "fmt"
        "io"
        "os"
    
        "github.com/spf13/viper"
    )
    
    type cfgFile struct {
        Config map[string]string
    }
    
    func (c *cfgFile) Marshal(w io.Writer) error {
        for k, v := range c.Config {
            if _, err := fmt.Fprintf(w, "%s = %s
    ", k, v); err != nil {
                return err
            }
        }
        return nil
    }
    
    func (c *cfgFile) Unmarshal(r io.Reader) error {
        c.Config = make(map[string]string)
        var key, value string
        for {
            _, err := fmt.Fscanf(r, "%s = %s
    ", &key, &value)
            if err != nil {
                if err == io.EOF {
                    break
                }
                return err
            }
            c.Config[key] = value
        }
        return nil
    }
    
    func main() {
        // Create a new Viper instance.
        v := viper.New()
    
        // Set the configuration file type to use the custom cfgFile type.
        v.SetConfigType("cfg")
    
        // Set the configuration file path.
        v.SetConfigFile("config.cfg")
    
        // Set the configuration file type marshaler and unmarshaler.
        v.SetConfigMarshaler(&cfgFile{}, viper.MarshalFunc(func(v interface{}, w io.Writer) error {
            return v.(*cfgFile).Marshal(w)
        }))
        v.SetConfigTypeUnmarshaler("cfg", viper.UnmarshalFunc(func(r io.Reader, v interface{}) error {
            return v.(*cfgFile).Unmarshal(r)
        }))
    
        // Read the configuration file.
        if err := v.ReadInConfig(); err != nil {
            fmt.Printf("Error reading config file: %s
    ", err)
            return
        }
    
        // Get a value from the configuration.
        value := v.GetString("key")
        fmt.Println(value)
    
        // Set a value in the configuration.
        v.Set("key", "value")
    
        // Write the configuration to the file.
        if err := v.WriteConfig(); err != nil {
            fmt.Printf("Error writing config file: %s
    ", err)
            return
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      相关资源
      最近更新 更多