Skip to main content
This guide will walk you through creating a complete working example using go-homedir to detect the home directory and expand paths.

Complete Example

1

Create a new Go file

Create a file named main.go with the following code:
main.go
package main

import (
    "fmt"
    "log"
    "github.com/mitchellh/go-homedir"
)

func main() {
    // Get the home directory
    dir, err := homedir.Dir()
    if err != nil {
        log.Fatal("Error getting home directory:", err)
    }
    fmt.Println("Home directory:", dir)

    // Expand paths with ~ prefix
    paths := []string{
        "~/.config",
        "~/Documents/projects",
        "~/.ssh/id_rsa",
        "/absolute/path",  // This won't be expanded
    }

    fmt.Println("\nExpanded paths:")
    for _, path := range paths {
        expanded, err := homedir.Expand(path)
        if err != nil {
            log.Printf("Error expanding %s: %v\n", path, err)
            continue
        }
        fmt.Printf("  %s -> %s\n", path, expanded)
    }
}
2

Run the program

Execute your program:
go run main.go
3

Review the output

You should see output similar to:
Home directory: /home/username

Expanded paths:
  ~/.config -> /home/username/.config
  ~/Documents/projects -> /home/username/Documents/projects
  ~/.ssh/id_rsa -> /home/username/.ssh/id_rsa
  /absolute/path -> /absolute/path
The actual home directory path will vary based on your operating system and username.

Core Functions

Dir() - Get Home Directory

The Dir() function returns the home directory for the current user:
dir, err := homedir.Dir()
if err != nil {
    // Handle error - home directory could not be detected
    log.Fatal(err)
}
fmt.Println(dir)
Key Features:
  • Automatically caches the result for better performance
  • Uses OS-specific detection methods
  • Returns an error if the home directory cannot be determined

Expand() - Expand Tilde Paths

The Expand() function expands ~ in paths to the full home directory:
path, err := homedir.Expand("~/.config/app")
if err != nil {
    log.Fatal(err)
}
fmt.Println(path)
// Output: /home/username/.config/app
Behavior:
  • Only expands paths starting with ~ followed by / or \
  • Returns the path unchanged if it doesn’t start with ~
  • Returns an error for user-specific home directories like ~otheruser/path
  • Handles empty paths gracefully

Advanced Usage

Disabling Cache

By default, go-homedir caches the home directory. You can disable this:
import "github.com/mitchellh/go-homedir"

func main() {
    // Disable caching
    homedir.DisableCache = true

    dir, err := homedir.Dir()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(dir)
}

Resetting Cache

If you need to clear the cache (useful in tests):
// Clear the cache
homedir.Reset()

// Next call to Dir() will re-detect the home directory
dir, err := homedir.Dir()

Practical Use Cases

package main

import (
    "fmt"
    "path/filepath"
    "github.com/mitchellh/go-homedir"
)

func getConfigPath(appName string) (string, error) {
    configPath := fmt.Sprintf("~/.config/%s/config.yaml", appName)
    return homedir.Expand(configPath)
}

func main() {
    path, err := getConfigPath("myapp")
    if err != nil {
        panic(err)
    }
    fmt.Println("Config path:", path)
    // Output: Config path: /home/username/.config/myapp/config.yaml
}

Common Patterns

Building File Paths

Combine homedir.Dir() with filepath.Join() for robust path construction:
import (
    "path/filepath"
    "github.com/mitchellh/go-homedir"
)

home, err := homedir.Dir()
if err != nil {
    log.Fatal(err)
}

configPath := filepath.Join(home, ".config", "myapp", "settings.json")

User Input Processing

Expand user-provided paths that might contain ~:
func processUserPath(userInput string) (string, error) {
    // Expand ~ if present
    expanded, err := homedir.Expand(userInput)
    if err != nil {
        return "", fmt.Errorf("invalid path: %w", err)
    }

    // Convert to absolute path
    absPath, err := filepath.Abs(expanded)
    if err != nil {
        return "", fmt.Errorf("could not resolve path: %w", err)
    }

    return absPath, nil
}

Next Steps

API Reference

Explore all available functions and options

Examples

See more real-world usage examples

Build docs developers (and LLMs) love