2015-04-07 28 views
2

我想将我在Golang中的配置加载器类从特定的配置文件结构转换为更一般的配置。本来,我所定义的结构与一组特定于程序的变量,例如:Golang接口和接收器 - 需要的建议

type WatcherConfig struct { 
    FileType string 
    Flag  bool 
    OtherType string 
    ConfigPath string 
} 

我然后定义两个方法用指针接收器:

func (config *WatcherConfig) LoadConfig(path string) error {} 

func (config *WatcherConfig) Reload() error {} 

我现在试图使这个更通用,并且计划是定义一个接口Config并且在这个上定义LoadConfigReload方法。然后,我可以为每个需要它的模块创建一个struct,并保存自己重复一个基本上打开文件,读取JSON并将其转储到结构中的方法。

我试图创建一个接口,定义这样的方法:

type Config interface { 
    LoadConfig(string) error 
} 
func (config *Config) LoadConfig(path string) error {} 

但是,这显然是引发错误的Config不是一个类型,它是一个接口。我需要为我的班级添加更抽象的struct吗? 知道所有配置结构将具有ConfigPath字段可能会有用,因为我将此用于Reload()配置。

我很确定我正在讨论这个错误的方法,或者我正在尝试做的不是一个在Go中很好地工作的模式。我真的很感激一些建议!

  • 我想在Go中做什么?
  • Go是一个好主意吗?
  • 什么是替代Go-ism?
+0

为什么定义的时候你可以创建FUNC LoadConfig(路径字符串)(配置,错误){}的方法? – Makpoc

回答

3

即使你使用嵌入两个接口和实施中,Config.LoadConfig()实现无法知道嵌入它的类型(例如WatcherConfig)。

最好是不要执行此为方法但作为简单帮手工厂功能。

你可以做这样的:

func LoadConfig(path string, config interface{}) error { 
    // Load implementation 
    // For example you can unmarshal file content into the config variable (if pointer) 
} 

func ReloadConfig(config Config) error { 
    // Reload implementation 
    path := config.Path() // Config interface may have a Path() method 
    // for example you can unmarshal file content into the config variable (if pointer) 
} 
+0

啊,这很有道理!我错过了'config.Path()'方法的想法,以确保配置对象有一个路径字符串。好一个! – shearn89