douwen5584 2014-05-11 15:38
浏览 234
已采纳

从Go中的main导入本地包

I'm writing an API using Go and its net/http stdlib module and i have some utils code in a directory named utils. But when i import them in main, Go does not find the packages. The root cause is apparently the fact that Go packages have to be saved in $GOPATH/src/. So i wanted to know if there was a way to import local packages and save them in the same folder as the main package.

I'm following the Github Directory Structure so my $GOPATH looks like that.

$GOPATH/src/
   |___github.com/
       |___user/
           |___repository/
               |___main.go
               |___utils/
                   |___core.go
                   |___factory.go

As the utils directory is really tied to the app, it would be really bad for me to save it as a different Go app in $GOPATH/src. And apart from that, imagine the moment when i will want to push my code on Github. Here it's only 2 repositories but if it was 6 i would need 6 private repos for really related and tied parts of a single application.

  • 写回答

1条回答 默认 最新

  • doupo5178 2014-05-12 01:31
    关注

    (Documenting an answer as it looks unanswered at first glance)

    The package declaration on both files should be package utils and they should be imported with:

    import "github.com/user/repository/utils"
    

    Its also possible to make sub-packages (standard library io package has io/ioutil) if you really want to separate each code file as separate packages.

    import "github.com/user/repository/utils"
    import "github.com/user/repository/utils/sub"
    

    The local directory structure would be:

    $GOPATH/src/
       |___github.com/
           |___user/
               |___repository/
                   |___main.go
                   |___utils/
                       |___core.go
                       |___sub/factory.go
    

    (Answer details posted in comment by @phndiaye)

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

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址