我正在尝试通过创建一个 JSON 文件并将其解析为结构体来配置我的 Go 程序:
var settings struct {
serverMode bool
sourceDir string
targetDir string
}
func main() {
// then config file settings
configFile, err := os.Open("config.json")
if err != nil {
printError("opening config file", err.Error())
}
jsonParser := json.NewDecoder(configFile)
if err = jsonParser.Decode(&settings); err != nil {
printError("parsing config file", err.Error())
}
fmt.Printf("%v %s %s", settings.serverMode, settings.sourceDir, settings.targetDir)
return
}
config.json文件:
{
"serverMode": true,
"sourceDir": ".",
"targetDir": "."
}
程序编译并运行时没有出现错误,但print语句输出如下内容:false
(false和两个空字符串)
我也尝试使用json.Unmarshal(..)
,但结果相同。
如何以填充结构值的方式解析JSON?
configFile, err := os.Open("config.json")
后添加defer configFile.Close()
。 - Kiril