0Pricing
Go Academy · Lesson

Binding to Structs

Unmarshal config.

From Loose Keys to a Struct

Calling GetString everywhere scatters string keys through your code. Unmarshaling config into a typed struct gives you compile-time field names and one place to see the shape.

Defining a Config Struct

Declare a struct whose fields carry mapstructure tags so Viper knows which config key maps to which field. Each field is followed by a tag such as mapstructure:"host" written between backquotes in real Go source.

type ServerConfig struct {
    Host string // tag: mapstructure host
    Port int    // tag: mapstructure port
}

type Config struct {
    Server ServerConfig // tag: mapstructure server
    Debug  bool         // tag: mapstructure debug
}

All lessons in this course

  1. Reading Config Files
  2. Environment Variables
  3. Defaults and Watching
  4. Binding to Structs
← Back to Go Academy