Platform-agnostic way to get a user's home directory in Go

Getting a user’s home directory in a platform-agnostic manner is easy through the os.UserHomeDir() method introduced in Go v1.12. It retrieves the current user’s home directory which is:

  • The $HOME environmental variable in Linux and macOS.
  • %USERPROFILE% in Windows.

Here’s how to use it:

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(homeDir)
}
Output
/home/ayo # Linux
/home/ayo # macOS
C:\Users\ayo # Windows

Another option is to get the current user account and access the HomeDir property on it as shown below:

package main

import (
	"fmt"
	"log"
	"os/user"
)

func main() {
	currentUser, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	homeDir := currentUser.HomeDir
	fmt.Println(homeDir)
}
Output
/home/ayo # Linux
/home/ayo # macOS
C:\Users\ayo # Windows

Thanks for reading, and happy coding!