I'm trying to convert my config loader class in Golang from a specific config file structure to a more general one. Originally, I defined a struct with a set of program-specific variables, for example:
type WatcherConfig struct {
FileType string
Flag bool
OtherType string
ConfigPath string
}
I then defined two methods with pointer receivers:
func (config *WatcherConfig) LoadConfig(path string) error {}
and
func (config *WatcherConfig) Reload() error {}
I'm now attempting to make this more general, and the plan was to define an interface Config
and define the LoadConfig
and Reload
methods on this. I could then create a struct
with the config layout for each module that needed it, and save myself repeating a method that basically opens a file, reads JSON, and dumps it into a struct.
I've tried creating an interface and defining a method like this:
type Config interface {
LoadConfig(string) error
}
func (config *Config) LoadConfig(path string) error {}
But that is obviously throwing errors as Config
is not a type, it's an interface. Do I need to add a more abstract struct
to my class? It may be useful to know that all configuration structs will have the ConfigPath
field, as I use this to Reload()
the config.
I'm fairly sure I'm going about this the wrong way, or what I'm trying to do isn't a pattern that works nicely in Go. I'd really appreciate some advice!
- Is what I'm trying to do possible in Go?
- Is it a good idea in Go?
- What would be the alternative Go-ism?