How to Build a 12-Factor App in Go

Web
Build a 12-Factor App in Go by externalizing configuration to environment variables and designing stateless processes for scalable deployment.

You build a 12-Factor App in Go by externalizing configuration via environment variables and ensuring stateless processes. Use os.Getenv to read settings like database URLs or API keys directly from the environment, avoiding hardcoded values in your source code.

package main

import (
	"fmt"
	"os"
)

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	fmt.Printf("Listening on port %s\n", port)
}
  1. Store secrets and config in environment variables instead of code. Run export PORT=8080 before starting your app.
  2. Ensure your application is stateless by storing session data in an external cache like Redis rather than local memory.
  3. Deploy your compiled binary to a container or VM that can scale horizontally without shared state.
  4. Use a process manager to handle the lifecycle of your Go binary, treating it as an ephemeral process.