Created
December 4, 2023 18:21
-
-
Save PzaThief/27c74ebaa4d64bbff71deb9870875d27 to your computer and use it in GitHub Desktop.
golang get current directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"path/filepath" | |
"runtime" | |
) | |
func main() { | |
fmt.Println(Getwd()) | |
fmt.Println(GetExecutable()) | |
fmt.Println(GetArg()) | |
fmt.Println(GetDirName()) | |
} | |
// Return root/cwd in case of run binary in build directory with cwd working directory | |
// Return root/cwd in case of go run .. with cwd working directory | |
func Getwd() string { | |
wd, _ := os.Getwd() | |
return wd | |
} | |
// Return root/build in case of run binary in build directory with cwd working directory | |
// Return temporary directory in case of go run .. with cwd working directory | |
func GetExecutable() string { | |
ex, _ := os.Executable() | |
exPath := filepath.Dir(ex) | |
return exPath | |
} | |
// Return root/build in case of run binary in build directory with cwd working directory | |
// Return temporary directory in case of go run .. with cwd working directory | |
func GetArg() string { | |
dir, _ := filepath.Abs(filepath.Dir(os.Args[0])) | |
return dir | |
} | |
// Return root in case of run binary in build directory with cwd working directory | |
// Return root in case of go run .. with cwd working directory | |
// Even in other computers, it returns same directory which ran go build | |
func GetDirName() string { | |
_, filename, _, _ := runtime.Caller(0) | |
return filepath.Dir(filename) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment