Getting uid and gid of a file

Viewed 5843

In linux the stat struct contains the UID and GID of a file.

Is there a way to obtain the same information (UID and GID) of a file using Go(lang)?

1 Answers

I figured out a reasonable way to do it.

import (
    "syscall"
    "os"
)

info, _ := os.Stat("/path/to/the/file")

var UID int
var GID int
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
    UID = int(stat.Uid)
    GID = int(stat.Gid)
} else {
    // we are not in linux, this won't work anyway in windows, 
    // but maybe you want to log warnings
    UID = os.Getuid()
    GID = os.Getgid()
}
Related