Welcome To Golang By Example

Get current Username in Go (Golang)

Overview

‘os/user’ package can be used to get the current user name.

Let’s see a working code

Code

package main

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

func main() {

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

	username := user.Username

	fmt.Printf("Username: %s\n", username)
}

Output

Username: "someusername"