[Golang] 取得使用者的Home資料夾位置

golang 有提供 user的package

可以直接取得使用者的資訊

在文件裡面寫到

user.Current() 可以取得包含目前使用者資訊的User struct

struct結構長這樣

type User struct {
        // Uid is the user ID.
        // On POSIX systems, this is a decimal number representing the uid.
        // On Windows, this is a security identifier (SID) in a string format.
        // On Plan 9, this is the contents of /dev/user.
        Uid string
        // Gid is the primary group ID.
        // On POSIX systems, this is a decimal number representing the gid.
        // On Windows, this is a SID in a string format.
        // On Plan 9, this is the contents of /dev/user.
        Gid string
        // Username is the login name.
        Username string
        // Name is the user's real or display name.
        // It might be blank.
        // On POSIX systems, this is the first (or only) entry in the GECOS field
        // list.
        // On Windows, this is the user's display name.
        // On Plan 9, this is the contents of /dev/user.
        Name string
        // HomeDir is the path to the user's home directory (if they have one).
        HomeDir string
}

其中的HomeDir是可以直接存取的

所以完整程式碼如下:

import (
        "fmt"
        "os/user"
)

func main () {
        usr := user.Current()

        fmt.Println(usr.HomeDir)
}

 

看更多