golang获取路径 2022-10-19
2022-10-18 本文已影响0人
9_SooHyun
以下两种方式可以获取binary的路径
-
os.Args
hold the command-line arguments, starting with the program name.
os.Args provides access to raw command-line arguments. Note that the first value in this slice is the path to the program, and os.Args[1:] holds the arguments to the program.
NOTE: Args is not generated by Go, but just passed on from whatever started the application. So os.Args[0] may be the abs path of a binary or a relative path of a binary, depending on the command-line input
// command-line-arguments.go
package main
import (
"fmt"
"os"
)
func main() {
argsWithProg := os.Args
argsWithoutProg := os.Args[1:]
arg := os.Args[3]
fmt.Println(argsWithProg)
fmt.Println(argsWithoutProg)
fmt.Println(arg)
}
// $ go build command-line-arguments.go
// $ ./command-line-arguments a b c d
// [./command-line-arguments a b c d]
// [a b c d]
// c
-
os.Executable().
Executable returns the path name for the executable that started the current process. Executable returns an absolute path unless an error occurred. The main use case is finding resources located relative to an executable. 顾名思义,返回binary所在的绝对路径
package main
import "os"
func main() {
println("- os.Executable() result:")
exepath, _ := os.Executable()
println("I am ", exepath)
}
以下两种方式可获取“绝对路径”
-
os.Getwd() 获得执行命令时的绝对路径
translates to a system call. It's your shell and OS that's responsible for the values. Getwd returns a rooted path name corresponding to the current directory
os.Getwd() 打印的是执行命令时的路径
root@path1 # command // 此时 os.Getwd() 得到path1
root@path2 # command // 此时 os.Getwd() 得到path2
-
runtime.Caller(0).
Caller reports file and line number information about function invocations on the calling goroutine's stack. 0 identifies the caller of Caller, which means current file's code, so we can use runtime.Caller(0) to get abs path of the current file where the code is being executed
// go playground code
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"path"
"runtime"
)
func main() {
var abPath string
// 0 identifies the caller of Caller, which means current file's code
_, filename, _, ok := runtime.Caller(0)
if ok {
abPath = path.Dir(filename)
}
fmt.Println(abPath, filename)
}
// output: /tmp/sandbox200883588 /tmp/sandbox200883588/prog.go
注意,runtime.Caller(0)返回的是编译时刻的源码文件信息(文件名称、代码行号等)
How to embed files into Go binaries
I have some text file that I read from my Go program. I'd like to ship a single executable, without supplying that text file additionally. How do I embed it into compilation on Windows and Linux?
典型场景是,项目使用一些json文件存储某些内容,go程序依赖这些json文件,那么发布该程序的时候必然要带上这些json文件,那是否可以在编译期间读取这些文件并保存到go变量,这样可以直接发布二进制程序而无需牵扯一堆的json文件
Starting with Go 1.16, released in Feb 2021, we can use the go:embed
directive to finish this