Golang for Admins Vol 2: Users

Golang for Admins Vol. 2: Users

The Setup

If you’re like me, you probably found Kelsey Hightower’s talk from Gophercon 2014 Go for Sysadmins. If you haven’t watched it, go check it out. You’ll get pumped up and start wanting to pickup Go even more.

So he briefly describes how Go is so easy to get things like system user information. A lightbulb goes on, and I think “hey! I can do that too”.

Break Out the Manual

You have two options: Check out the pkg from the official documentation page, or use our awesome local godoc server from our first Golang blog.

Check out 2 key components: The User struct, and the method Current(). It looks like the Current() method returns a User type, and a possible error. We’re going to use the common pattern for error checking:

User, error := user.Current()
if error != nil{
    // Do something here if an error occured

This is a standard pattern you can see more patterns like these in some of the links below. Now after careful inspection of the package documentation, we are ready to take a crack at the challenge.

// userinfo shows information of the current user.

package main

import (

func main() {
    thisUser, error := user.Current()
    if error != nil {
        fmt.Printf("Something bad happened: %s\n", error)
        thisUser.Username, thisUser.Uid, thisUser.Gid, thisUser.HomeDir)

We are outputting the current user’s information. Their username, UID, GID, and home directory. The output once compiled should look something like this:

User    bobby
UID:    1000
GID:    1000
Home:   /home/bobby

Challenge to the Reader

Given your newfound knowledge about getting user data, can you determine how to get information about another user besides the current user, using the os/user library?

Wrap Up

This was a fun & quick post for me. I was hoping to share a little bit about a library that a Sysadmin or Engineer could find useful. If you enjoyed the blog and want to support me, feel free to pickup one of these great books off Amazon. So far I’ve only put up books I’ve read and got something out of. Thanks for reading, see you at part III.


SRE, former Release Engineer, Pythonista, Gopher, Rube Goldberg Machine Untangler, Amateur Photographer. My thick skulled opinions are my own.