🧱 fix GetWorkdir method in prod mode

This commit is contained in:
warjiang
2023-06-15 15:26:44 +08:00
parent 78b43bd894
commit 53fe50c528

View File

@@ -1,6 +1,7 @@
package util package util
import ( import (
"log"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@@ -8,35 +9,41 @@ import (
"strings" "strings"
) )
func GetCurrentAbsPath() string { func GetCurrentAbsPath() (string, bool) {
// 最终方案-全兼容 // Work in dev and prod runtime
dir := getCurrentAbPathByExecutable() isDebug := false
absDir := getCurrentAbsPathByExecutable()
tmpDir, _ := filepath.EvalSymlinks(os.TempDir()) tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
// 如果是临时目录或者是goland运行的目录那么就用caller的方式获取 // If it is a temporary directory or the directory contains 'GoLand' keyword,
if strings.Contains(dir, tmpDir) || strings.Contains(dir, "GoLand") { // then retrieve it using the `caller` method.
return getCurrentAbPathByCaller() if strings.Contains(absDir, tmpDir) || strings.Contains(absDir, "GoLand") {
isDebug = true
return getCurrentAbsPathByCaller(), isDebug
} }
return dir return absDir, isDebug
} }
func GetWorkdir() string { func GetWorkdir() string {
currentAbsPath := GetCurrentAbsPath() workDir, isDebug := GetCurrentAbsPath()
workDir := filepath.Join(currentAbsPath, "..") if isDebug {
workDir = filepath.Join(workDir, "..")
}
return workDir return workDir
} }
// 获取当前执行文件绝对路径 // getCurrentAbsPathByExecutable Retrieve the absolute path to the currently executing file.
func getCurrentAbPathByExecutable() string { func getCurrentAbsPathByExecutable() string {
exePath, err := os.Executable() exePath, err := os.Executable()
log.Printf("executable path: %s", exePath)
if err != nil { if err != nil {
panic(err) panic(err)
} }
res, _ := filepath.EvalSymlinks(filepath.Dir(exePath)) res, _ := filepath.EvalSymlinks(exePath)
return res return path.Dir(res)
} }
// 获取当前执行文件绝对路径(go run // getCurrentAbsPathByCaller Retrieve the absolute path to the currently executing file.by `go run`
func getCurrentAbPathByCaller() string { func getCurrentAbsPathByCaller() string {
var abPath string var abPath string
_, filename, _, ok := runtime.Caller(0) _, filename, _, ok := runtime.Caller(0)
if ok { if ok {