Getting a User Home Dot Path with Go

This recipe looks up the current user’s home directory and returns a path to a . file that matches the name of the executable program being run. For example, if this were included in a foo.go, which compiles into foo for user rob, then it would return something like /home/rob/.foo.

package main

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

func main() {
  fmt.Println(HomeDotDir())
}

func HomeDotDir() string {
    usr, err := user.Current()
    if err != nil {
        panic(err)
    }
    return path.Join(usr.HomeDir, "."+path.Base(os.Args[0]))
}