user的结构:
type User struct { Uid string // user id Gid string // primary group id Username string Name string HomeDir string }
user包中的主要函数:
type User func Current() (*User, error) func Lookup(username string) (*User, error) func LookupId(uid string) (*User, error)
事例1 windows:
package main import ( "fmt" "os/user" ) func main() { usr, error := user.Current() if error == nil { fmt.Println(usr) } } [ `go run testuser.go` | done: 7.5934343s ] &{S-1-5-21-2450167352-2372647358-1749370957-1000 S-1-5-21-2450167352-2372647358-1749370957-513 City-PC\City C:\Users\City}
事例2 windows:
package main import ( "fmt" "os/user" ) func main() { usr, error := user.Current() if error == nil { fmt.Println(usr.Uid) fmt.Println(usr.Gid) fmt.Println(usr.Username) fmt.Println(usr.Name) fmt.Println(usr.HomeDir) _usr, error1 := user.Lookup(usr.Username) if error1 == nil { fmt.Println(_usr) } else { fmt.Println(error1.Error()) } } else { fmt.Println(error.Error()) } } [ `go run testuser.go` | done: 14.3608214s ] S-1-5-21-2450167352-2372647358-1749370957-1000 S-1-5-21-2450167352-2372647358-1749370957-513 City-PC\City C:\Users\City &{S-1-5-21-2450167352-2372647358-1749370957-1000 unknown City-PC\City Unknown directory}事例3 windows:
package main import ( "fmt" "os/user" ) func main() { usr, error := user.Current() if error == nil { fmt.Println(usr.Uid) fmt.Println(usr.Gid) fmt.Println(usr.Username) fmt.Println(usr.Name) fmt.Println(usr.HomeDir) _usr, error1 := user.Lookup(usr.Uid) if error1 == nil { fmt.Println(_usr) } else { fmt.Println(error1.Error()) } } else { fmt.Println(error.Error()) } } [ `go run testuser.go` | done: 7.5694329s ] S-1-5-21-2450167352-2372647358-1749370957-1000 S-1-5-21-2450167352-2372647358-1749370957-513 City-PC\City C:\Users\City No mapping between account names and security IDs was done.
好像uid查询 在windows上不怎么起作用
包的bug提示:
Lookup and LookupId functions do not set Gid and HomeDir fields in the User struct returned on windows.
Linux,Fedora19
code:
package main import( "fmt" "os/user" ) func PrintUsr(usr *user.User){ fmt.Println("------------------------------") fmt.Println("Uid: ",usr.Uid) fmt.Println("Gid: ",usr.Gid) fmt.Println("Username: ",usr.Username) fmt.Println("Name: ",usr.Name) fmt.Println("HomeDir: ",usr.HomeDir) } func main(){ usr,_ := user.Current() PrintUsr(usr) user1,_:=user.Lookup(usr.Name) PrintUsr(user1) user2,_:=user.LookupId(usr.Uid) PrintUsr(user2) }
Result:
[jjy@localhost user]$ go run testuser.go ------------------------------ Uid: 1000 Gid: 1000 Username: jjy Name: jjy HomeDir: /home/jjy ------------------------------ Uid: 1000 Gid: 1000 Username: jjy Name: jjy HomeDir: /home/jjy ------------------------------ Uid: 1000 Gid: 1000 Username: jjy Name: jjy HomeDir: /home/jjy
有疑问加站长微信联系(非本文作者)