duanji9264 2018-01-30 10:11
浏览 28
已采纳

将一个主程序包放在cmd / myapp子目录中可以吗?

this is my first Go project and I have had a hard time grasping the different documents on code organization (e.g. I found it somewhat hard to tell which ones have been superceded, or apply to deprecated vendoring tools/approaches). I finally settled on Ben Johnson's Standard Package Layout, with a very slim root package (in the root directory of my project) and most code in internal/pkg/...

However, I've added a cmd/myapp dir and put my main.go file for the executable program in there, since I understood that to be a common pattern.

So now I have:

myapp
|
+- myapp.go   // "package myapp", with only type and interface declarations and no imports
|
+- cmd
|   |
|   +- main.go // "package main", with import gitlab.tld/username/myapp, gitlab.tld/username/myapp/internal/pkg/routing etc.
|
+- internal
    |
    +- pkg
        |
        +- routing
        |    |
        |    +- routing.go // "package routing"
        |
        +- sql 
        |
        +- etc.

Now, when I go to cmd/myapp and call go build, it builds fine and leaves an executable that does what it's supposed to do right there. But when I call go build -v from the project's main directory, no executable is produced. In fact, only myapp.go seems to be processed which contains only type definitions. (And of course, go install does not produce a binary either. go get -v gitlab.tld/username/myapp also does not seem to do anything.)

So I have the suspicion that this is not how it is meant after all, but I am not even so sure about that. Is there a problem with the project layout, or did I get the usage of go tooling wrong?

Thanks for any help you might provide to this go newbie,

Andreas

  • 写回答

1条回答 默认 最新

  • dongzhao8233 2018-01-30 10:59
    关注

    When you run go build or go install the command expects a list of packages to process. If no import paths are given, the action applies to the package in the current directory.

    So if there is no package main in your root directory, no executable will be produced.

    The command doesn't look in subdirectories. You may have multiple commands in your cmd directory. In this case it won't know which one to build. And building all of them every time is wasteful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮