How to Use Configuration Files (JSON, YAML, TOML) in Go

Use encoding/json for JSON files and third-party libraries like gopkg.in/yaml.v3 or github.com/BurntSushi/toml to load YAML and TOML configurations into Go structs.

Go does not natively support loading configuration from JSON, YAML, or TOML files into structs using a single built-in function; you must use the standard encoding/json package for JSON or third-party libraries like gopkg.in/yaml.v3 and github.com/BurntSushi/toml for the others. For JSON, read the file bytes and unmarshal them directly into your struct using json.Unmarshal. For YAML and TOML, you must first import the respective third-party library and use their Unmarshal functions with the same file bytes pattern.

package main

import (
	"encoding/json"
	"os"
)

type Config struct {
	Port int    `json:"port"`
	Name string `json:"name"`
}

func main() {
	data, err := os.ReadFile("config.json")
	if err != nil {
		panic(err)
	}
	var cfg Config
	if err := json.Unmarshal(data, &cfg); err != nil {
		panic(err)
	}
	println(cfg.Name)
}

For YAML, replace encoding/json with gopkg.in/yaml.v3 and json.Unmarshal with yaml.Unmarshal. For TOML, replace with github.com/BurntSushi/toml and use toml.Unmarshal.