Ben Chuanlong Du's Blog

It is never too late to learn.

Get Information of User in Golang

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Get Information of the Current User

user.Current() returns information of the current (real) user. If the code is run by a non-root user named some_user on Linux, then information of some_user is returned. However, if some_user has sudo access and run the code using sudo, then the real user user is root and the information of root is returned.

In [1]:
import "os/user"
In [2]:
currentUser, err := user.Current()
In [3]:
currentUser
Out[3]:
&{1000 1000 dclong dclong /home/dclong}
In [4]:
currentUser.Username
Out[4]:
dclong
In [5]:
currentUser.Uid
Out[5]:
1000
In [6]:
currentUser.Gid
Out[6]:
1000

Test An User's Access to a Path

Use unix.Access

In [1]:
import "golang.org/x/sys/unix"
In [6]:
unix.Access("/home", unix.R_OK) == nil
Out[6]:
true
In [4]:
unix.Access("/home", unix.W_OK)
Out[4]:
permission denied
In [7]:
unix.Access("/tmp", unix.W_OK) == nil
Out[7]:
true

Use os.OpenFile + os.IsPermission

This way only works on files. Please refer to Golang : Test file read write permission example for detailed discussions.

In [8]:
import "os"
In [12]:
os.OpenFile("/home", os.O_WRONLY, 0666)
Out[12]:
<nil> open /home: is a directory
In [ ]:
 

Comments