英文:
Multiple applications built from one directory
问题
我有一个简单的Go项目,其中包括一个Web应用程序、一个工作程序和一个共享文件。这些文件分别是web.go、worker.go和shared.go(例如)。
如何使用"go install"命令从这个设置中创建两个可执行文件?如果我将这3个文件放在一起,会出现"main在此块中重新声明"的错误,因为我在同一个包中有两个main函数。
我真的不想将这3个文件拆分成3个不同的目录,并在子目录中创建2个入口点以逻辑上分离它们。
如何在同一个目录中保持它们并编译出两个可执行文件?
英文:
I have a simple Go project which is a web application, a worker application, and a shared file. These are in files web.go, worker.go, and shared.go (for example).
How can I "go install" to create the 2 binaries from this setup? If I just put all 3 files together, I get error main redeclared in this block
because I have 2 main functions in the same package.
I really don't want to split these 3 files into 3 different directories with the 2 entry points in subdirectories created just to seperate them logically.
How can I keep them in the same directory and compile 2 executables?
答案1
得分: 4
清洁的解决方案是创建三个单独的目录。一个用于Web程序,一个用于工作程序,还有一个用于两者共享的包。
另外,你也可以使用构建约束来控制你的构建过程。例如,GAE就使用这种方法,通过提供一个"appengine"构建标签,可以在使用GAE时提供不同的主程序。在这种情况下,你需要在文件开头添加一个任意的构建标签(例如// +build worker
),然后相应地调用go构建工具,包括你的构建标签(类似于go build -tags worker
)应该可以工作。
英文:
The clean solution is to create three separate directories. One for the web program, one for the worker program and a shared package for both of them.
Alternatively, you can also use build constraints to control your build. GAE uses this approach for example, by providing an "appengine" build tag that can be used to provide a different main when using GAE. In this case, you would need to add an arbitrary build tag to the beginning of your files (e.g. // +build worker
) and invoke the go build tool accordingly, by including your build tags (something like go build -tags worker
) should probably work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论