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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.