Getwd Anchors Relative Paths
Resolve the process working directory with os.Getwd and join it with filepath.Join so relative config paths become absolute without string concatenation.
Code
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// 进程启动目录是相对路径的锚点
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
fmt.Println("cwd:", cwd)
// 用 Join 而不是手写 "/":跨平台且自动清理多余分隔符
config := filepath.Join(cwd, "config", "app.yaml")
fmt.Println("config:", config)
fmt.Println("is abs config:", filepath.IsAbs(config))
// 对照:不含 cwd 的 Join 只做清理与拼接,结果仍是相对路径,
// 不依赖也不锚定 cwd——变abs与否取决于是否以分隔符开头
relativePath := filepath.Join("etc", "app.yaml")
fmt.Println("relative join:", relativePath)
fmt.Println("is abs relativePath:", filepath.IsAbs(relativePath))
}The flow at a glance
Getwd Anchors Relative Paths is built around the function main.
Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
Points of care
- No package manager involved — every call resolves to a built-in API.
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Putting it to use
Signature: func main()
Output lines are prefixed (cwd:, config:, is abs config:), which puts each step’s effect in plain sight.
Core statements
if err != nil {
panic(err)
}
Interactive Tools for This Topic
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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.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 is the error handling style?
- The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
- What does Getwd Anchors Relative Paths print when run?
- The script runs standalone; its 5 labeled outputs include `cwd:`, `config:`, `is abs config:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.