Ben Chuanlong Du's Blog

It is never too late to learn.

Get Directory Information in Golang

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [3]:
import "os"

Current Working Directory

In [4]:
path, err := os.Getwd()
In [6]:
path
Out[6]:
/workdir/archives/blog/misc/content/2022/07/get-the-current-working-directory-in-golang

Path of the Golang Executable

In [7]:
path, err := os.Executable()
In [9]:
path
Out[9]:
/usr/local/go/bin/gophernotes

Home Directory of the Current User

UserHomeDir returns the current (real) user's home directory. If the code is run by a non-root user named some_user on Linux, then the returned home directory is /home/some_user. However, if some_user has sudo access and run the code using sudo, then the real user user is root and the returned home directory is /root.

In [4]:
path, err := os.UserHomeDir()
In [5]:
path
Out[5]:
/home/dclong
In [ ]:
 

Comments