Skip to main content

How to Retrieve File Ownership Information in Golang

·2 mins

Figuring out how to retrieve the ownership of a file on my Linux workstation from within a Go program was not that evident the first time that I tried. By ownership I mean the uid and gid values associated with a file. This post describes how I did it.

Let’s assume that the variable path holds the name of a file. The entry point is the os.stat function which returns a FileInfo structure:

info, err := os.Stat(path)

Using the info structure above you can invoke the Sys() function, which returns the Stat structure defined in the syscall package:

stat := info.Sys().(*syscall.Stat_t)

The (*syscall.Stat_t) type assertion is necessary because the function Sys() is defined to return the empty interface (interface{}).

Finally, you can retrieve the file’s uid and gid from the stat structure above as follows:

uid := stat.Uid
gid := stat.Gid

Note that uid and gid are uint32 values.

Getting the User and Group Names #

You can retrieve the user and group names using the os/user package. First, you need to covert the uint32 variables into strings:

u := strconv.FormatUint(uint64(uid), 10)
g := strconv.FormatUint(uint64(gid), 10)

Now you can retrieve the desired usr and group strings:

usr, err := user.LookupId(u)
group, err := user.LookupGroupId(g)

A Sample Go Program #

A complete Go program implementing the steps above is available from my Gitlab repository; it is called ugid. Here is a sample output:

$ bin/ugid README.md /etc/magic /dev/mem
README.md: pedro, pedro (1000, 1000)
/etc/magic: root, root (0, 0)
/dev/mem: root, kmem (0, 15)