這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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 mainimport ("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 mainimport ("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-1000S-1-5-21-2450167352-2372647358-1749370957-513City-PC\CityC:\Users\City&{S-1-5-21-2450167352-2372647358-1749370957-1000 unknown City-PC\City Unknown directory}
案例3 windows:
package mainimport ("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-1000S-1-5-21-2450167352-2372647358-1749370957-513City-PC\CityC:\Users\CityNo 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 mainimport( "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: 1000Gid: 1000Username: jjyName: jjyHomeDir: /home/jjy------------------------------Uid: 1000Gid: 1000Username: jjyName: jjyHomeDir: /home/jjy------------------------------Uid: 1000Gid: 1000Username: jjyName: jjyHomeDir: /home/jjy