英文:
Import local package from main in Go
问题
我正在使用Go编写一个API,使用了net/http
标准库模块,并且我在一个名为utils的目录中有一些工具代码。但是当我在主程序中导入它们时,Go找不到这些包。根本原因似乎是Go包必须保存在$GOPATH/src/
目录中。所以我想知道是否有一种方法可以导入本地包并将它们保存在与主包相同的文件夹中。
我遵循了Github的目录结构,所以我的$GOPATH看起来像这样:
$GOPATH/src/
|___github.com/
|___user/
|___repository/
|___main.go
|___utils/
|___core.go
|___factory.go
由于utils目录与应用程序紧密相关,将其保存为$GOPATH/src中的不同Go应用程序对我来说是非常糟糕的。除此之外,想象一下当我想要将代码推送到Github时的情况。这里只有2个存储库,但如果有6个存储库,我将需要6个私有存储库来保存一个单一应用程序的相关部分。
英文:
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
得分: 4
(将答案记录下来,因为乍一看它看起来没有回答)
两个文件的package
声明应该是package utils
,并且应该使用以下方式导入:
import "github.com/user/repository/utils"
如果你真的想将每个代码文件分开作为单独的包,也可以创建子包(标准库io
包有io/ioutil
)。
import "github.com/user/repository/utils"
import "github.com/user/repository/utils/sub"
本地目录结构应该是:
$GOPATH/src/
|___github.com/
|___user/
|___repository/
|___main.go
|___utils/
|___core.go
|___sub/factory.go
(由@phndiaye在评论中发布的答案详细信息)
英文:
(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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论