Reading Config Files
Load YAML, JSON, TOML.
Reading Config Files is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Configuration Lives Outside Code
Hardcoding values like ports, hostnames, and timeouts into your Go program is fragile. Viper is the de-facto configuration library for Go: it reads settings from files, environment variables, flags, and remote stores.
In this lesson you load configuration from a file on disk.
What Formats Viper Reads
Viper supports many formats out of the box:
- YAML (
.yaml/.yml) - JSON (
.json) - TOML (
.toml) - HCL, INI, and Java properties files
You pick the format with SetConfigType, or Viper infers it from the file extension.
Installing and Importing Viper
Add Viper to your module and import it:
go get github.com/spf13/viperimport "github.com/spf13/viper"
Because Viper is an external dependency, snippets that import it are not runnable in this lesson player. We simulate the behavior with the standard library where we can.
import "github.com/spf13/viper"Telling Viper Where to Look
You configure the file name, type, and search paths before reading:
viper.SetConfigName("config")sets the base name (no extension)viper.SetConfigType("yaml")sets the formatviper.AddConfigPath(".")adds a directory to search
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("/etc/myapp")Reading the File
Call viper.ReadInConfig() to load the file. It returns an error you must check:
- A missing file returns a
ConfigFileNotFoundError - A malformed file returns a parse error
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("failed to read config: %v", err)
}A Sample YAML Config
Imagine a config.yaml like this. Viper flattens nested keys using dots, so the port becomes server.port.
server:
port: 8080
host: "localhost"
debug: trueGetting Typed Values
Viper exposes typed getters so you avoid manual conversions:
viper.GetInt("server.port")viper.GetString("server.host")viper.GetBool("debug")
port := viper.GetInt("server.port")
host := viper.GetString("server.host")
debug := viper.GetBool("debug")
fmt.Println(host, port, debug)JSON Works the Same Way
Switching to JSON only changes the file content and the config type. The same key paths and getters apply. This portability is why Viper is popular: your code does not care which format ops chose.
{
"server": { "port": 8080, "host": "localhost" },
"debug": true
}TOML Is Also Supported
TOML is common in the Go ecosystem (many CLIs use it). The same nested keys map to dotted paths.
[server]
port = 8080
host = "localhost"
debug = trueParsing JSON With the Standard Library
To see the idea work for real, here is plain Go parsing JSON config without Viper, using only encoding/json into a map (Viper itself works on a generic map under the hood).
package main
import (
"encoding/json"
"fmt"
)
func main() {
raw := "{\"port\":8080,\"host\":\"localhost\"}"
var c map[string]any
if err := json.Unmarshal([]byte(raw), &c); err != nil {
panic(err)
}
fmt.Printf("%v:%v\n", c["host"], c["port"])
}Runnable: Reading Into a Map
This self-contained program parses JSON config into a generic map and prints values, mirroring what Viper does under the hood for JSON.
package main
import (
"encoding/json"
"fmt"
)
func main() {
raw := "{\"port\":8080,\"host\":\"localhost\"}"
var m map[string]any
json.Unmarshal([]byte(raw), &m)
fmt.Println("host:", m["host"])
fmt.Println("port:", m["port"])
}Quick Check
Test your understanding of reading config files with Viper.
Recap
You learned how Viper reads config files:
- It supports YAML, JSON, and TOML transparently
- Configure with
SetConfigName,SetConfigType,AddConfigPath ReadInConfig()loads the file and returns an error- Typed getters like
GetIntandGetStringread values by dotted key
Next: overriding config with environment variables.
Frequently asked questions
Is the “Reading Config Files” lesson free?
Yes — the full text of “Reading Config Files” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Reading Config Files”?
Load YAML, JSON, TOML. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Reading Config Files” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Reading Config Files
- Environment Variables
- Defaults and Watching
- Binding to Structs