How to get current directory in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, we are going to learn how to get the current directory in golang?, here we will use the os.Getwd() method to get the working directory, and fmt.Println() to print dir in the golang console.

The os.Getwd() method returns the dir path as a string, when I run this code in the online golang program runner, I got /runtime/go/3y3ksm8ze.

Well, let’s dive into a code…

package main
// More info on Getwd()
// https://golang.org/src/os/getwd.go
// 
import(
  "os" 
  "fmt"
  "log"
)

func main() {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(dir)
}

When we run the above program, we will get our directory as a string.

Let’s see the actual output of the code.

get, current directory, golang

Try it yourself

All the best 👍

Follow me on Twitter