Go from Zero 09. Errors Example

Read a Config File

Parse key-value settings from a text file with error handling.

Sample app.conf:

# App settings
host = localhost
port = 8080
debug = true

The Go program that reads and parses it:

package main

import (
	"fmt"
	"os"
	"strings"
)

func readConfig(filename string) (map[string]string, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("could not read %s: %s", filename, err)
	}

	config := map[string]string{}
	lines := strings.Split(string(data), "\n")

	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}

		key := strings.TrimSpace(parts[0])
		value := strings.TrimSpace(parts[1])
		config[key] = value
	}

	return config, nil
}

func main() {
	config, err := readConfig("app.conf")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	for key, value := range config {
		fmt.Printf("%s = %s\n", key, value)
	}
}

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy