gpt4 book ai didi

go - 我应该如何在 go 中导入自己的内部包?

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:49 24 4
gpt4 key购买 nike

我正在尝试使用(非官方)Standard Go Project Layout 制作 Go 应用程序.我不明白的是我应该如何在 internal 目录中导入包。

This is my project

使用将 internal 目录复制到 $GOPATH 的 Dockerfile,它可以工作:

~/go/src/project-layout$ docker build --no-cache .
(...)
Step 5/7 : RUN ls -la /go/src
---> Running in a27235b0bbef
total 24
drwxrwxrwx 1 root root 4096 Apr 29 07:05 .
drwxrwxrwx 1 root root 4096 Apr 12 22:23 ..
-rw-rw-r-- 1 root root 556 Apr 29 06:06 README.md
drwxrwxr-x 3 root root 4096 Apr 29 06:08 app
drwxr-xr-x 1 root root 4096 Apr 29 07:05 myproject
drwxrwxr-x 3 root root 4096 Apr 29 06:11 pkg
Removing intermediate container a27235b0bbef
---> bb924f8f88f0
Step 6/7 : RUN go build -o myapp ./cmd/myapp/main.go
---> Running in 06bd6cd778d2
Removing intermediate container 06bd6cd778d2
---> 31184f9224c8
Step 7/7 : RUN ./myapp
---> Running in baf75d4dd503
Hello World, from myapp main
Hello world, from myapp internals
Hello world, from myprivatelib: 'myapp internal'
Hello world, from myprivatelib: 'myapp main'
Removing intermediate container baf75d4dd503
---> 5747b6b4686f
Successfully built 5747b6b4686f

但是,当我尝试在本地构建时,我得到:

~/go/src/project-layout$ go build -o myapp ./cmd/myapp/main.go
cmd/myapp/main.go:6:2: cannot find package "app/myapp" in any of:
/home/comavn/go/src/project-layout/vendor/app/myapp (vendor tree)
/usr/lib/go-1.10/src/app/myapp (from $GOROOT)
/home/comavn/go/src/app/myapp (from $GOPATH)
cmd/myapp/main.go:7:2: cannot find package "pkg/myprivatelib" in any of:
/home/comavn/go/src/project-layout/vendor/pkg/myprivatelib (vendor tree)
/usr/lib/go-1.10/src/pkg/myprivatelib (from $GOROOT)
/home/comavn/go/src/pkg/myprivatelib (from $GOPATH)

我可以通过在 vendor 目录中符号链接(symbolic link) internal/appinternal/pkg 来让它工作,但这似乎是错误的...

那么,我在这里做错了什么?我应该如何导入这些内部包?

最佳答案

我想我找到了正确的解决方案:https://github.com/ComaVN/project-layout/commit/6415a8f06dd7fbdcf1c7282bc3ec172c3e145611

您还必须使用项目名称导入:

import (
"project-layout/internal/app/myapp"
"project-layout/internal/pkg/myprivatelib"
)

不幸的是,这确实意味着构建取决于项目使用的确切目录名称。

关于go - 我应该如何在 go 中导入自己的内部包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55898667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com