Preface
- It is often necessary to get the current working directory in go language development, such as when you need to load configuration files, write debugging, error logs, etc.
- The current working directory of a go program is usually different in development, production, and test environments, which makes it troublesome to get the current working directory of the program under different circumstances.
- Next, we will introduce several common methods of getting the current working directory in go language, and introduce their related features.
os.Getwd() returns the root path relative to one of the current directories
os.Executable() returns the absolute path to the executable of the current process
The path will contain the name of the executable file. In conjunction with filepath.Dir()
returns the directory where the executable is located.
os.TempDir() returns the default path where temporary files are stored
runtime.Caller returns information about the file and line number of the function call on the stack of the calling goroutine
main.go Complete Code
|
|
dir/dir.go
|
|
Next, let’s look at the data returned by each method in different modes
-
The current working directory is
/Users/snowlyg/go/src/github.com/snowlyg/learns
and executego run path/main.go
-
The current working directory is
/Users/snowlyg/go/src/github.com/snowlyg/learns
, executego build -o path/main path/main.go
, then execute the path/main file -
The current working directory is
/Users/snowlyg/go/src/github.com/snowlyg/learns
, executego test -timeout 30s -v -run ^TestPath$ github.com/snowlyg/learns/path/dir
Ref
https://blog.snowlyg.com/dir/