How to Add a Configuration File to a Go CLI App

Cli
Define a struct, create a JSON file, and use encoding/json to load settings into your Go CLI app.

Add a configuration file by defining a struct to hold settings, parsing the file into that struct, and loading it in your main function. Use the encoding/json package to unmarshal a config.json file into your configuration struct.

package main

import (
	"encoding/json"
	"os"
)

type Config struct {
	Port     int    `json:"port"`
	Database string `json:"database"`
}

func main() {
	file, _ := os.Open("config.json")
	var cfg Config
	json.NewDecoder(file).Decode(&cfg)
}