문제

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.

도움이 되었습니까?

해결책

(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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top