Get the Current Username, Name and Home Dir (Cross Platform)

· 159 words · 1 minute read

In this example we get the current user, the user who is executing the program, and their details. These details include information like user id (Uid), username (the short version of their name), name (the user’s full name) and the user’s home directory location. To do this we use the os/user package. This package also handles the differences between OS like *nix vs. windows very well, keeping your code simple across all platforms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

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

func main() {

    user, err := user.Current()
    if err != nil {
        panic(err)
    }

    // Current User
    fmt.Println("Hi " + user.Name + " (id: " + user.Uid + ")")
    fmt.Println("Username: " + user.Username)
    fmt.Println("Home Dir: " + user.HomeDir)

    // Get "Real" User under sudo.
    // More Info: https://stackoverflow.com/q/29733575/402585
    fmt.Println("Real User: " + os.Getenv("SUDO_USER"))
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!