登录
首页 >  Golang >  Go问答

让 Go 识别何时将新行添加到 TOML 配置文件中

来源:stackoverflow

时间:2024-04-08 12:15:38 344浏览 收藏

哈喽!今天心血来潮给大家带来了《让 Go 识别何时将新行添加到 TOML 配置文件中》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我正在尝试使用 toml 配置文件在 go 中创建一个简单的 cli 工具。我希望能够将我在其他工具的命令行上使用的常用命令存储在 toml 文件中,并使用我的 cli 程序来调用这些命令。我想让其他用户尽可能轻松地向 toml 文件添加新工具/命令。我遇到的问题是让 go 识别添加到 toml 配置文件中的新工具,而无需手动打开 config.go 文件并将该工具添加到保存解析的 toml 数据的配置结构中。 toml 配置示例:

# configuration file
#
[assetfinder]
default = "assetfinder -subs-only {{target}}"
silent = "assetfinder -subs-only {{target}} --silent"

[subfinder]
default = "subfinder -u {{target}}"
silent = "subfinder -u {{target}} --silent"

我希望用户能够添加另一个工具/命令,而不必接触源代码并将其手动添加到结构中。这是 config.go:

package config

import (
    "github.com/spf13/viper"
)

type Config struct {
    Assetfinder map[string]string
    Subfinder map[string]string
}

func Load() (*Config, error) {
    v := viper.New()
    v.SetConfigName("config")
    v.AddConfigPath(".")
    err := v.ReadInConfig()
    if err != nil {
        return nil, err
    }
    c := &Config{}
    err = v.Unmarshal(c)
    return c, err
}

正确答案


viper 有一个关于“观看并重新读取配置文件”的解决方案。 https://github.com/spf13/viper#watching-and-re-reading-config-files

您只需注册onconfigchange事件并调用watchconfig即可:

err := v.ReadInConfig()
if err != nil {
    return nil, err
}
viper.OnConfigChange(func(e fsnotify.Event) {
    fmt.Println("Config file changed:", e.Name)
    // TODO: read config from viper and update you logic
})
viper.WatchConfig()

watchconfig 实现位于 https://github.com/spf13/viper/blob/master/viper.go#L431

  1. 它使用fsnotify来监视文件更改
  2. 文件创建/写入时,调用readinconfig进行更新
  3. 触发 onconfigchange 事件

本篇关于《让 Go 识别何时将新行添加到 TOML 配置文件中》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>