golang获取路径 2022-10-19

2022-10-18  本文已影响0人  9_SooHyun

以下两种方式可以获取binary的路径

// 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
package main

import "os"

func main() {
    println("- os.Executable() result:")
    exepath, _ := os.Executable()
    println("I am ", exepath)
}

以下两种方式可获取“绝对路径”

root@path1 # command // 此时 os.Getwd() 得到path1
root@path2 # command // 此时 os.Getwd() 得到path2
// 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

上一篇 下一篇

猜你喜欢

热点阅读