I'm using the Decoder
from package encoding/json
to decode a JSON configuration file into a struct. The field names have a different case (lowercase first character in struct because of visibility concerns) in the file and struct so I'm using struct field tags as described in the documentation. The Problem is that Decoder
seems to ignore these tags and the struct fields are empty. Any ideas what's wrong with my code?
{
"DataSourceName": "simple-blog.db"
}
type Config struct {
dataSourceName string `json:"DataSourceName"`
}
func loadConfig(fileName string) {
file, err := os.Open(fileName)
if err != nil {
log.Fatalf("Opening config file failed: %s", err)
}
defer file.Close()
decoder := json.NewDecoder(file)
config = &Config{} // Variable config is defined outside
err = decoder.Decode(config)
if err != nil {
log.Fatalf("Decoding config file failed: %s", err)
}
log.Print("Configuration successfully loaded")
}
loadConfig("config.json")
log.Printf("DataSourceName: %s", config.dataSourceName)
2017/10/15 21:04:11 DB Name:
You need to export your dataSourceName
field as encoding/json
package requires them to be so