User Config Dir Path Resolution
Resolve per-user config and cache directories through os.UserConfigDir with an explicit fallback when the platform variable is unset.
Code
package main
import (
"fmt"
"os"
"path/filepath"
)
// 应用配置目录:<UserConfigDir>/<app>,平台变量缺失时报错而非猜测
func appConfigDir(app string) (string, error) {
root, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("user config dir unavailable: %w", err)
}
return filepath.Join(root, app), nil
}
// 缺失平台变量时的显式降级:UserConfigDir 报错就退回 UserHomeDir,
// 按 XDG 约定拼 ~/.config(Windows 上 UserConfigDir 读 %AppData%,很少走到降级)
func appConfigDirFallback(app string) (string, error) {
root, err := os.UserConfigDir()
if err != nil {
home, homeErr := os.UserHomeDir()
if homeErr != nil {
return "", fmt.Errorf("no config root: %v; no home dir: %w", err, homeErr)
}
root = filepath.Join(home, ".config")
}
return filepath.Join(root, app), nil
}
func main() {
dir, err := appConfigDir("devtool")
if err != nil {
fmt.Println("resolve failed:", err)
dir, err = appConfigDirFallback("devtool")
if err != nil {
fmt.Println("fallback failed:", err)
return
}
}
fmt.Println("config dir:", dir)
// UserHomeDir 是另一个常用锚点:~/.local/state 约定放运行时状态
if home, err := os.UserHomeDir(); err == nil {
fmt.Println("state dir:", filepath.Join(home, ".local", "state", "devtool"))
}
}How it works
User Config Dir Path Resolution comes down to the functions appConfigDir, appConfigDirFallback and main.
Every fallible call checks err != nil (4 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
Signature: func appConfigDir(app string) (string, error)
Running the file prints labeled results such as resolve failed:, fallback failed:, config dir: — each operation’s effect is visible in the output.
Running the file executes main, which drives appConfigDir and appConfigDirFallback in order.
Key statements
return "", fmt.Errorf("user config dir unavailable: %w", err)
if err != nil {
home, homeErr := os.UserHomeDir()
if homeErr != nil {
return "", fmt.Errorf("no config root: %v; no home dir: %w", err, homeErr)
}
root = filepath.Join(home, ".config")
}
if err != nil {
fmt.Println("resolve failed:", err)
dir, err = appConfigDirFallback("devtool")
if err != nil {
fmt.Println("fallback failed:", err)
return
}
}
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do errors reach the caller?
- As returned `error` values, checked at 4 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- What does User Config Dir Path Resolution print when run?
- No setup needed: run the file and look for labeled lines like `resolve failed:`, `fallback failed:`, `config dir:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.