英文:
go run command doesn't pick up non-go files in the same path
问题
文件夹结构:
- dev.env
- go.mod
- main.go
dev.env:
ENV="DEV"
PASSWORD="DEV!@#$%&"
main.go:
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/joho/godotenv"
)
var environment string
func init() {
fmt.Println("ENV: ", environment)
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
devEnvPath := filepath.Join(dir, "dev.env")
_ = godotenv.Load(devEnvPath)
}
func main() {
fmt.Println("PASSWORD", os.Getenv("PASSWORD"))
}
命令:
go run -ldflags="-X 'main.environment=DEV'" .
输出:
ENV: DEV
PASSWORD
它可以使用go build
命令正常工作,但是不知道为什么不能使用go run
命令。
英文:
Folder structure:
- dev.env
- go.mod
- main.go
dev.env:
ENV="DEV"
PASSWORD="DEV!@#$%"
main.go:
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/joho/godotenv"
)
var environment string
func init() {
fmt.Println("ENV: ", environment)
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
devEnvPath := filepath.Join(dir, "dev.env")
_ = godotenv.Load(devEnvPath)
}
func main() {
fmt.Println("PASSWORD", os.Getenv("PASSWORD"))
}
Command:
go run -ldflags="-X 'main.environment=DEV'" .
Output:
ENV: DEV
PASSWORD
It works with go build
but curious why it doesn't work with go run
答案1
得分: 3
作为一般规则,在最简单的用例中不要使用go run
,因为它是Go社区中最常见的"footgun"(指容易导致问题的工具)。
正如@Marc指出的,错误源于go run
二进制文件是在临时目录中构建的。为了保持简单,只需在目录中使用相对路径。这对于go build
和go run
都适用:
dir := "."
devEnvPath := filepath.Join(dir, "dev.env")
err := godotenv.Load(devEnvPath)
if err != nil {
log.Fatal(err)
}
英文:
As a general rule, don't use go run
unless in the most trivial of use cases - it is the most common footgun in the Go community.
As @Marc pointed out the error stems from the go run
binary is built in a temporary directory. To keep things simple, just use a relative path in your directory. This will work for both go build
& go run
:
dir := "."
devEnvPath := filepath.Join(dir, "dev.env")
err := godotenv.Load(devEnvPath)
if err != nil {
log.Fatal(err)
}
答案2
得分: 1
从Go 1.16开始,从包含包源代码的目录访问文件的最简单方法是使用//go:embed
和embed
包将这些文件嵌入到编译后的二进制文件中:
//go:embed dev.env
var devEnv string
func init() {
m, err := godotenv.Unmarshal(devEnv)
…
}
英文:
As of Go 1.16, the simplest way to access files from the directory containing a package's source code is to use //go:embed
and the embed
package to embed those files into the compiled binary:
//go:embed dev.env
var devEnv string
func init() {
m, err := godotenv.Unmarshal(devEnv)
…
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论