Overview
go-homedir is a lightweight Go library that detects the user’s home directory without requiring cgo. This makes it ideal for cross-compilation environments where cgo dependencies can cause issues.
The Problem with os/user
The built-inos/user package in Go requires cgo on Darwin (macOS) systems. This dependency prevents Go code from being cross-compiled to macOS targets. However, most use cases for os/user are simply to retrieve the home directory for the current user - something that can be done without cgo.
go-homedir solves this problem by providing a pure Go implementation that works across all platforms.
Key Features
No cgo Required
Pure Go implementation enables seamless cross-compilation to any platform
Cross-Platform
Supports Unix, Linux, macOS, Windows, and Plan 9 systems
Built-in Caching
Automatically caches the home directory for improved performance
Path Expansion
Expands
~ in paths to the full home directoryHow It Works
The library uses OS-specific methods to detect the home directory:- Unix/Linux: Checks
$HOMEenvironment variable, falls back togetent passwd, then shell commands - macOS: Checks
$HOMEenvironment variable, falls back todsclcommand - Windows: Checks
%USERPROFILE%,%HOME%, or combines%HOMEDRIVE%and%HOMEPATH% - Plan 9: Uses the
$homeenvironment variable
Quick Preview
Here’s a simple example of usinggo-homedir:
Next Steps
Installation
Install go-homedir in your Go project
Quickstart
Build your first application with go-homedir