构建 Golang 项目的正确方法

huangapple go评论67阅读模式
英文:

Building Golang project properly

问题

我有一个项目结构,看起来像这样:

构建 Golang 项目的正确方法
我计划只使用一个 shell 脚本(build.sh)来设置 GOPATH 并构建项目。

我不确定如何正确构建一个 Golang 项目,我短期目标只是构建 src 目录中的包,并将二进制文件放入 bin 目录。

我不确定 go build 命令能否实现这一点,我尝试了一些方法。

所以首先我的问题是 - 这个项目结构合理吗?其次,我如何将我的 src 目录编译到 bin 目录?

我的尝试给我以下错误:

can't load package: package .: no buildable Go source files in /home/oleg/WebstormProjects/oresoftware/stack-server

所以我认为我需要告诉 Go 在 src 目录中查找,因为 Go 只会在项目根目录中查找 .go 文件,但我不确定如何做到这一点。

如果有关系的话,main.go 文件的包名是 "main"。

英文:

I have a project structure that looks like so:

构建 Golang 项目的正确方法
I was planning on just using a shell script (build.sh) to set GOPATH and build the project.

I am not sure how to build a Golang project properly, my short term goal is to just to build the packages in the src directory and put the binaries into the bin directory.

I am not sure what go build command can do that, I have tried a few things.

So first my question is - is this a reasonable project structure and second, how can I compile my src directory to bin?

What I have gives me the following error:

can't load package: package .: no buildable Go source files in /home/oleg/WebstormProjects/oresoftware/stack-server

So I believe I need to tell Go to look in the src directory, because Go is only looking for .go files in the project root, but I am not sure how to do that.

If it matters, the main.go file has a package name of "main".

答案1

得分: 3

以下是翻译好的内容:

GOPATH=$PROJECT_DIR && cd $PROJECT_DIR && go install main

同时将你的 main.go 文件移动到 src/main/main.go。

这将生成一个 bin/main 可执行文件。

如果你想要构建多个可执行文件,你需要将每个 main.go 文件放入单独的文件夹/包中。生成的可执行文件的名称取自文件所在的目录名。main.go 文件的包名必须始终为 main,以便创建一个二进制文件。

要编译多个可执行文件,你需要使用:

GOPATH=$PROJECT_DIR && cd $PROJECT_DIR && go install ...

... 匹配所有的文件夹/包。

英文:
GOPATH=$PROJECT_DIR && cd $PROJECT_DIR && go install main

Also move your main.go file into src/main/main.go.

This will produce a bin/main executable.

If you have multiple executables you wanna build, you have to put each main.go file into a separate folder/package. The name of the generated executable is taken from the directory name the file is inside. The package name of the main.go files must always be main if it should create a binary.

To compile multiple executables you have to use:

GOPATH=$PROJECT_DIR && cd $PROJECT_DIR && go install ...

The ... matches all folders/packages.

huangapple
  • 本文由 发表于 2017年1月18日 11:43:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/41710989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定