• Go 获取当前项目路径 支持go run go build 两种方式


    Go 获取当前项目路径,通过 os.Executable() go run 和go build是不同的路径。

    提供通用的解决方法如下:

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "path"
        "path/filepath"
        "runtime"
        "strings"
    )
    
    func main() {
        fmt.Println("getTmpDir(当前系统临时目录) = ", os.TempDir())
        fmt.Println("getCurrentAbPathByExecutable(仅支持go build) = ", getCurrentAbPathByExecutable())
        fmt.Println("getCurrentAbPathByCaller(仅支持go run) = ", getCurrentAbPathByCaller())
        fmt.Println("getCurrentAbPath(最终方案-全兼容) = ", getCurrentAbPath())
    }
    
    // 最终方案-全兼容
    func getCurrentAbPath() string {
        dir := getCurrentAbPathByExecutable()
        tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
        if strings.Contains(dir, tmpDir) {
            return getCurrentAbPathByCaller()
        }
        return dir
    }
    
    // 获取当前执行文件绝对路径
    func getCurrentAbPathByExecutable() string {
        exePath, err := os.Executable()
        if err != nil {
            log.Fatal(err)
        }
        res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
        return res
    }
    
    // 获取当前执行文件绝对路径(go run)
    func getCurrentAbPathByCaller() string {
        var abPath string
        _, filename, _, ok := runtime.Caller(0)
        if ok {
            abPath = path.Dir(filename)
        }
        return abPath
    }
  • 相关阅读:
    在JavaScript中对HTML进行反转义
    JavaScript 删除数组中的对象
    CSS中的before和:after伪元素深入理解
    关于css浮动的一点思考
    前端常见跨域解决方案(全)
    window.location对象详解
    51nod 1001 数组中和等于K的数对
    51nod 1002 数塔取数问题
    51nod 1015 水仙花数
    51nod 1080 两个数的平方和
  • 原文地址:https://www.cnblogs.com/zhaoyingjie/p/16038348.html
Copyright © 2020-2023  润新知