我尝试通过配置文件 (yaml) 配置 CLI 应用程序。该应用程序有几个“组件”(比方说持久层、集成网络服务器等)。这些组件在子包中进行管理,以保持代码整洁。这些组件的配置在它们的包中定义 并在配置包中“合并”到表示配置文件的结构。将此代码视为演示实现:
package main
import (
"errors"
"fmt"
yaml "gopkg.in/yaml.v2"
)
//
// This would be in package 'webserver'
// Only the Config part is shown, there would be a constructor and the implementation of
// the webserver as well...
//
// WebserverConfig holds all required configuration params
type WebserverConfig struct {
Listen string `yaml:"listen"`
Autostart bool `yaml:"autostart"`
}
// Validate checks if all fields make sense and returns a list of error string if problems
// are found
func (wsc WebserverConfig) Validate() (error, []string) {
errs := []string{}
if wsc.Listen == "" {
errs = append(errs, "Field 'listen' must not be empty.")
}
if len(errs) > 0 {
err := errors.New("Config of 'webserver' has errors")
return err, errs
}
return nil, errs
}
// UnmarshalYAML implements a custom unmarshaller to make sure defaults are set
// to meaningful values
func (wsc *WebserverConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
type WebserverConfigDefaulted WebserverConfig
var defaults = WebserverConfigDefaulted{
Listen: ":8080",
Autostart: true,
}
out := defaults
err := unmarshal(&out)
*wsc = WebserverConfig(out)
return err
}
//
// This would be in package conf
//
//
// Config is the global configuration composed of all component configuration sections
type Config struct {
Webserver WebserverConfig `yaml:"webserver"`
}
// Load reads the bytes into the global config
func Load(data string) (Config, error) {
c := Config{}
err := yaml.Unmarshal([]byte(data), &c)
if err != nil {
return c, fmt.Errorf("Error while unmarshalling configuration from yaml: %s", err.Error())
}
return c, nil
}
// Validate should call each individual component configurations validate function (if it exists)
func (c Config) Validate() error {
// TODO: IMPLEMPNT...
return nil
}
//
// This is finally in main
//
//
var yamlFile = `---
webserver:
listen: ":9999"
`
func main() {
c, err := Load(yamlFile)
if err != nil {
fmt.Println(err)
}
err = c.Validate()
if err != nil {
fmt.Println(err)
}
}
在这里的 Playground 上找到它(因为 dep 到 yaml 而没有运行):https://play.golang.org/p/i3EAZJP7aYz
问题:在这一点上,我不知道如何实现全局验证函数 func (c Config) Validate() error 来调用“组件配置”的所有验证函数(例如func (wsc WebserverConfig) Validate()(错误,[]string))。有什么想法或提示吗?
最佳答案
我建议从 c.Validate() 调用 c.Webserver.Validate()。
这样做的缺点是每次添加新配置时都需要更新 c.Validate(),这可能很容易忘记。但是,它“简单、可读且明确”(引用您的评论)。
或者,您可以遍历配置的每个元素以查看哪些元素与 Validater 接口(interface)匹配,然后对它们调用 Validate。但是,这会更复杂,更难以理解和调试。通常的建议是避免反射,除非绝对必要。
关于go - 如何在 go 中实现碎片化的配置文件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49780496/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚