Config Struct

Load configuration from environment variables with flag overrides.

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
)

type Config struct {
	Port     string
	LogLevel string
	DBUrl    string
}

func getEnv(key, fallback string) string {
	if val := os.Getenv(key); val != "" {
		return val
	}
	return fallback
}

func mustGetEnv(key string) string {
	val, ok := os.LookupEnv(key)
	if !ok {
		log.Fatalf("required environment variable %s is not set", key)
	}
	return val
}

func LoadConfig() Config {
	cfg := Config{
		Port:     getEnv("PORT", "8080"),
		LogLevel: getEnv("LOG_LEVEL", "info"),
		DBUrl:    mustGetEnv("DATABASE_URL"),
	}
	flag.StringVar(&cfg.Port, "port", cfg.Port, "server port")
	flag.StringVar(&cfg.LogLevel, "log-level", cfg.LogLevel, "log level")
	flag.Parse()
	return cfg
}

func main() {
	cfg := LoadConfig()
	fmt.Printf("port=%s log_level=%s db=%s\n", cfg.Port, cfg.LogLevel, cfg.DBUrl)

	mux := http.NewServeMux()
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})
	log.Fatal(http.ListenAndServe(":"+cfg.Port, mux))
}

💻 Run locally

Copy the code above and run it on your machine

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