Reputation: 52
I have several configuration JSON files, each of which has a specific struc type for each file
currently I created a function per file/struct name:
type ConfigOne struct {
App string `json:"app"`
Web string `json:"web"`
Archive string `json:"archive"`
}
type ConfigTwo struct {
Options string `json:"options"`
Source string `json:"source"`
Backup bool `json:"backup"`
}
func ReadJsonConfigOne(file string, config *ConfigOne) error {
str := GetContentFile(file)
return json.Unmarshal([]byte(str), config)
}
func ReadJsonConfigTwo(file string, config *ConfigTwo) error {
str := GetContentFile(file)
return json.Unmarshal([]byte(str), config)
}
func main() {
One := ConfigOne{}
err := ReadJsonConfigOne("file_one.json", &One)
Two := ConfigTwo{}
err := ReadJsonConfigTwo("file_two.json", &Two)
../..
}
How to use only one function and passing a the struct as a parameter?
Upvotes: 0
Views: 39
Reputation: 5388
func ReadJsonConfig(file string, config interface{}) error {
str := GetContentFile(file)
return json.Unmarshal([]byte(str), config)
}
Usage
func main() {
One := ConfigOne{}
err := ReadJsonConfig("file_one.json", &One)
Two := ConfigTwo{}
err := ReadJsonConfig("file_two.json", &Two)
../..
}
Use interface as function parameter.
Upvotes: 3