User and group ID

Another piece of information that can be handy is the current user and the groups that the process belongs to. A typical user case could be to compare them with a file-specific permission.

The os package offers the following functions:

We can see that these three functions return IDs in their numerical form:

package main

import (
"fmt"
"os"
)

func main() {
fmt.Println("User ID:", os.Getuid())
fmt.Println("Group ID:", os.Getgid())
groups, err := os.Getgroups()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Group IDs:", groups)
}

The full example is available at https://play.golang.org/p/EqmonEEc_ZI.

In order to get the names of users and groups, there are some helper functions in the os/user package. These functions (with a pretty self-explanatory name) are as follows:

Even if the user ID is an integer, it takes a string as an argument, and so a conversion needs to be done. The easiest way to do that is to use the strconv package, which offers a series of utilities to convert from strings into the other basic data types, and vice versa.

We can see them in action in the following example:

package main

import (
"fmt"
"os"
"os/user"
"strconv"
)

func main() {
uid := os.Getuid()
u, err := user.LookupId(strconv.Itoa(uid))
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("User: %s (uid %d)\n", u.Username, uid)
gid := os.Getgid()
group, err := user.LookupGroupId(strconv.Itoa(gid))
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Group: %s (uid %d)\n", group.Name, uid)
}

The full example is available at https://play.golang.org/p/C6EWF2c50DT.