GolangNote

Golang笔记

golang 正确获取绝对路径的方法

Permalink

Golang编译出来之后是独立的可执行程序,路径的问题经常让人头疼,正确获取绝对路径非常重要, 方法如下:

获取绝对路径

Go: 获取绝对路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
    "fmt"
    "os"
    "os/exec"
    "path/filepath"
    "strings"
)

func main() {
    fmt.Println("GoLang 获取程序运行绝对路径")
    fmt.Println(GetCurrPath())
}

func GetCurrPath() string {
    file, _ := exec.LookPath(os.Args[0])
    path, _ := filepath.Abs(file)
    index := strings.LastIndex(path, string(os.PathSeparator))
    ret := path[:index]
    return ret
}

如果你在本地运行go run you.go,则输出:

plaintext: Absolute path
1
2
GoLang 获取程序运行绝对路径
/tmp/go-build183214745/command-line-arguments/_obj/exe

这是go 编译文件时生成的一个路径。不过很多时候需要读取配置,由于执行目录有时候不在程序所在目录。

新的方式获取:

Go: Absolute path
1
2
3
4
5
var abPath string
_, filename, _, ok := runtime.Caller(1)
if ok {
    abPath = path.Dir(filename)
}

在 golang playground 上运行

Go: 获取程序运行路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func main() {
	var abPath string
	_, filename, _, ok := runtime.Caller(1)
	if ok {
		abPath = path.Dir(filename)
	}
	fmt.Println(abPath)
	fmt.Println(GetCurrPath())

}

func GetCurrPath() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	index := strings.LastIndex(path, string(os.PathSeparator))
	ret := path[:index]
	return ret
}

输出:

plaintext: 输出
1
2
3
4
5
6
7
8
9
10
11
// golang playground 运行输出
/usr/local/go-faketime/src/runtime
/tmpfs

// 本地 go run xx.go 输出
/usr/local/go/src/runtime
/var/folders/bw/8bnjyv6j4k73h6j2qwh9s7xr0000gn/T/go-build3590385356/b001/exe

// go build 后运行二进制文件输出
/usr/local/go/src/runtime
/Users/root/goapps/src/codes/files // 二进制文件实际路径

看看自己需要哪个结果。。。

本文网址: https://golangnote.com/topic/40.html 转摘请注明来源

Related articles

Golang 单实例实现网站多域名请求

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 `http.Handler`。...

Write a Comment to "golang 正确获取绝对路径的方法"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms