我正在编写一个解析配置JSON文件的函数,并使用json.Unmarshal将其数据存储在结构中.我做了一些研究,它让我得到了一个点,我有一个Config结构和一个Server_Config结构作为配置中的一个字段,允许我添加更多的字段,因为我想要不同的配置类结构.
如何编写一个parseJSON函数来处理不同类型的结构?
码:
Server.go
type Server_Config struct {
html_templates string
}
type Config struct {
Server_Config
}
func main() {
config := Config{}
ParseJSON("server_config.json", &config)
fmt.Printf("%T\n", config.html_templates)
fmt.Printf(config.html_templates)
}
Run Code Online (Sandbox Code Playgroud)
config.go
package main
import(
"encoding/json"
"io/ioutil"
"log"
)
func ParseJSON(file string, config Config) {
configFile, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(configFile, &config)
if err != nil {
log.Fatal(err)
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果有更好的方法来做所有这些,请告诉我.对Go来说很新,我的大脑中刻有Java约定.
用途interface{}:
func ParseJSON(file string, val interface{}) {
configFile, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(configFile, val)
if err != nil {
log.Fatal(err)
}
}
Run Code Online (Sandbox Code Playgroud)
调用函数是一样的.