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

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.

package main

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

func main() {

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

    fmt.Println("Hello " + user.Name)
    fmt.Println("====")
    fmt.Println("Id: " + user.Uid)
    fmt.Println("Username: " + user.Username)
    fmt.Println("Home Dir: " + user.HomeDir)

}

Leave a Reply

Your email address will not be published. Required fields are marked *