Skip to content

Instantly share code, notes, and snippets.

@xcoulon
Last active November 19, 2017 15:31
Show Gist options
  • Save xcoulon/a7a382d5a1457c9c3ce9d1d1c4b1e1ef to your computer and use it in GitHub Desktop.
Save xcoulon/a7a382d5a1457c9c3ce9d1d1c4b1e1ef to your computer and use it in GitHub Desktop.
Nested structs in Golang (resource for the story on Medium)
type Config struct {
Server struct {
Host string `json:"host"`
Port string `json:"port"`
} `json:"server"`
Postgres struct {
Host string `json:"host"`
User string `json:"user"`
Password string `json:"password"`
DB string `json:"db"`
} `json:"database"`
}
func main() {
jsonConfig := []byte(`{
"server":{
"host":"localhost",
"port":"8080"},
"database":{
"host":"localhost",
"user":"db_user",
"password":"supersecret",
"db":"my_db"}}`)
var config Config
err := json.Unmarshal(jsonConfig, &config)
if err != nil {
panic(err)
}
fmt.Printf("Config: %+v\n", config)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment