在 Go 项目中访问静态文件

Accessing Static Files In Go Project

我在 ~/go/src/project-folder 中有一个具有以下结构的 go 项目

.
+--app
   +--main.go
   +--main (binary)
+--config
   +--config.go
+--.env

配置包使用 github.com/joho/godotenv 包加载 .env 文件,并在 main.go 中调用以访问某些数据(例如 运行 我的网络服务器的端口在)。

如果我 cd 进入 app 文件夹并且 运行 ./main 项目按预期工作但是如果我在说我的主目录并且 运行

~/go/src/project-folder/app/main

我明白了

open /.env: no such file or directoryError

我使用config包中的go包path/filepath访问.env文件

这是读取.env文件的配置包中的代码 config/config.go

package config

import (
    "github.com/joho/godotenv"
    "fmt"
    "path/filepath"
)

var env map[string]string 

func init() {
    envPath,_:= filepath.Abs("../.env");
    en, err := godotenv.Read(envPath)
    if err != nil {
        fmt.Print(err)
    }

    env = en
}

func ENV() map[string]string {
    return env
}

app/main.go

package main

import (
    "fmt"
    "net/http"
    "project/routes"
    "project/config"
    "project/models"
)

func main() {
    router := routes.MakeRouter()
    defer models.DB().Close()
    err := http.ListenAndServe(":" + config.ENV()["PORT"], router)
    if err != nil {
        fmt.Print(err)
    }
}

GOPATH GOPATH="/home/fanan/go"

好像路径是从我调用二进制文件的地方而不是二进制文件所在的地方引用的。

有没有办法确保路径是相对于二进制文件所在的位置而不是它被调用的位置?

It seems like the path is being referenced from where I call the binary file and not where the binary file is located.

当然是。这就是计算机和文件路径的工作方式。

向您的程序添加命令行标志或环境变量,以便您设置静态文件的路径。 (请注意,在 Go 二进制文件中绝对不可能找到源文件夹。)