Env Fallbacks With cmp.Or

cmp.Or returns the first non-zero argument, so environment fallback chains collapse into one line instead of nested if blocks per config key.

GoConfig Management

Code

gosnippet
21 lines
package main

import (
	"cmp"
	"fmt"
	"os"
)

func main() {
	// cmp.Or 逐个返回第一个非零值:env 缺省("")时落到下一级
	port := cmp.Or(os.Getenv("APP_PORT"), "8080")
	fmt.Println("port:", port)

	// 多级回退:全部为零值时返回零值本身
	name := cmp.Or(os.Getenv("APP_NAME"), "")
	fmt.Println("name is empty:", name == "")

	// 三级链条:专用变量 → 通用变量 → 写死的默认
	level := cmp.Or(os.Getenv("LOG_LEVEL"), os.Getenv("LEVEL"), "info")
	fmt.Println("level:", level)
}

How the snippet works

The snippet is organized around the function main.

Environment variables APP_PORT, APP_NAME, LOG_LEVEL, LEVEL drive configuration, so one artifact serves every environment.

What to watch for

  • The default toolchain covers the whole file — no additions required.

Applying it

The demo output is labeled (port:, name is empty:, level:), so the printed output reads as a trace of the operations performed.

Statements that matter most here

level := cmp.Or(os.Getenv("LOG_LEVEL"), os.Getenv("LEVEL"), "info")

Interactive Tools for This Topic

FAQ

What does Env Fallbacks With cmp.Or print when run?
Running the file directly is enough — expect labeled output lines such as `port:`, `name is empty:`, `level:`.