Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a file's group ID (GID) in Go?

Tags:

file

go

os.Stat() returns a FileInfo object, which has a Sys() method that returns an Interface{} with no methods.

Though I am able to fmt.Printf() it to "see" the "Gid", I am unable to access "Gid" programmatically.

How do I retrieve the "Gid" of a file here?

file_info, _ := os.Stat(abspath)
file_sys := file_info.Sys()
fmt.Printf("File Sys() is: %+v", file_sys)

Prints:

File Sys() is: &{Dev:31 Ino:5031364 Nlink:1 Mode:33060 Uid:1616 Gid:31 X__pad0:0 Rdev:0 Size:32 Blksize:32768 Blocks:0 Atim:{Sec:1564005258 Nsec:862700000} Mtim:{Sec:1563993023 Nsec:892256000} Ctim:{Sec:1563993023 Nsec:893251000} X__unused:[0 0 0]}

Note: I do not need a portable solution, it just has to work on Linux (notable because Sys() is known to be flaky).

Possibly related: Convert interface{} to map in Golang

like image 674
Elle Fie Avatar asked Jul 24 '19 23:07

Elle Fie


1 Answers

The reflect module showed that the data type for Sys()'s return is *syscall.Stat_t, so this seems to work to get the Gid of a file as a string:

file_info, _ := os.Stat(abspath)
file_sys := file_info.Sys()
file_gid := fmt.Sprint(file_sys.(*syscall.Stat_t).Gid)

Please let me know if there is a better way to do this.

like image 168
Elle Fie Avatar answered Nov 10 '22 21:11

Elle Fie