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)
}
- Store secrets and config in environment variables instead of code. Run
export PORT=8080before starting your app. - Ensure your application is stateless by storing session data in an external cache like Redis rather than local memory.
- Deploy your compiled binary to a container or VM that can scale horizontally without shared state.
- Use a process manager to handle the lifecycle of your Go binary, treating it as an ephemeral process.