/
home.go
59 lines (48 loc) · 979 Bytes
/
home.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package env
import (
"os"
"os/user"
"path/filepath"
"github.com/pkg/errors"
)
// ErrHomeNotFound HOME 目录找不到
var ErrHomeNotFound = errors.New("home path not found")
// Home 获取用户 Home 目录
func Home() (homePath string, err error) {
user, err := user.Current()
if err == nil {
homePath = user.HomeDir
return
}
homePath, err = unixHome()
if err == nil {
return
}
homePath, err = windowsHome()
return
}
func unixHome() (homePath string, err error) {
homePath = os.Getenv("HOME")
if homePath != "" {
return
}
homePath = os.Getenv("~")
if homePath != "" {
return
}
err = errors.WithStack(ErrHomeNotFound)
return
}
func windowsHome() (homePath string, err error) {
drive := os.Getenv("HOMEDRIVE")
path := os.Getenv("HOMEPATH")
if drive != "" && path != "" {
homePath = filepath.Join(drive, path)
return
}
homePath = os.Getenv("USERPROFILE")
if homePath == "" {
err = errors.WithStack(ErrHomeNotFound)
}
return
}