我有以下项目结构,在GOPATH.
. // Project root\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Dockerfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 .env\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 README.md\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.go\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.mod\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.sum\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 internal\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 somepackage\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.go\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 types.go\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 someother\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.go\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 oauth.go\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 types.go\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 models\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.go\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 pkg\n \xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 somepackage\n \xc2\xa0\xc2\xa0 \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.go\n \xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 anotherpackage\n \xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.go\nRun Code Online (Sandbox Code Playgroud)\n我想运行位于该src目录中的 Go 模块代码。\n当我cd进入该src目录和go run ./或go build .我的代码时,它可以完美运行。
当我站在项目的根部时,我无法运行go run ./src或go build ./src. 我收到以下错误。
src/service.go:8:2: cannot find package "web-service/internal/auth" in any of:\n /usr/lib/go/src/web-service/internal/auth (from $GOROOT)\n /home/miloertas/Packages/go/src/web-service/internal/auth (from $GOPATH)\nsrc/endpoints.go:3:8: cannot find package "web-service/internal/handlers" in any of:\n /usr/lib/go/src/web-service/internal/handlers (from $GOROOT)\n /home/miloertas/Packages/go/src/web-service/internal/handlers (from $GOPATH)\nRun Code Online (Sandbox Code Playgroud)\n我的源代码保留在这个src目录中很重要。\n同样重要的是我能够从项目的根目录中run获取build我的代码(例如该.env文件位于存储库的根目录中)。
因此,我正在寻找一种方法来从项目根目录中run访问build我的代码。src
我尝试将其移至go.mod项目的根目录并运行并运行go run ./src,但这会导致其自身的问题:
go中的所有子包internalpkg从Go 1.18开始,现在可以使用Go 工作区来实现这一点。
\n使用以下目录结构
\nparent-dir/\n\xe2\x94\x94\xe2\x94\x80 go.work\n hello-world/\n \xe2\x94\x9c\xe2\x94\x80 go.mod\n \xe2\x94\x94\xe2\x94\x80 main.go\nRun Code Online (Sandbox Code Playgroud)\nhello-world您可以从parent-dirusing运行该模块go run hello-world。
去工作
\ngo 1.18\n\nuse ./hello-world\nRun Code Online (Sandbox Code Playgroud)\ngo.mod
\nmodule hello-world\n\ngo 1.18\nRun Code Online (Sandbox Code Playgroud)\n注意:这是可能的,正如@Volker指出的那样,不推荐
\n