douqiao8032 2017-01-08 14:21
浏览 203

单个go项目使用的go包的正确文件夹结构

I am currently starting with Go and have already dug into the dos and don'ts regarding package naming and workspace folder structure.

Nevertheless, I am not quite sure how to properly organize my code according to the Go paradigm.

Here is my current structure example as it resides in $GOPATH/src:

github.com/myusername/project
|-- main.go
+-- internal
+---- config
|------ config.go

So i have the project called project which uses the config package which, in turn, is specialized in a way that it should only be used by project. Hence, I do not want it under github.com/myusername/config, right?

The question now is, is it "good" to use the internal package structure or should I instead put my project specific packages under github.com/myusername/$pkgname and indicate somehow that it belongs to project (e.g. name it projectconfig)?

  • 写回答

1条回答 默认 最新

  • dongyi1939 2017-01-09 00:16
    关注

    If your project produces one single program then the most common structure is the one you mentioned.

    If your project produces more than one program the common practice is using a structure like this:

    <project>/
      cmd/
        prog1/
          main.go
        prog2/
          main.go
    

    If your project exposes go code as library for third party consumption the most common structure is using the project's root dir to expose the domain model and API.

    <project>/
      model.go
      api.go
    

    This is for third party code to just import "github.com/user/project" and have the model and api available.

    Is common to see second and third options combined.

    Also is considered good practice to have packages for encapsulating dependencies usage. E.g. suppose your project uses the elastic search client

    <project>/
      cmd/
        prog1/
          main.go
      elastic/
        impl.go
      dao.go
      model.go
    

    So in dao.go you define the dao's API and then in elastic/impl.go you (import elastic library, domain modal and) define the implementation of DAO in terms of elastic. Finally you import everything from main.go which produces the actual program.

    See this great and short presentation about this issue.

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示