I try understand how to organize go code using "internal" packages. Let me show what the structure I have:
project/
internal/
foo/
foo.go # package foo
bar/
bar.go # package bar
main.go
# here is the code from main.go
package main
import (
"project/internal/foo"
"project/internal/bar"
)
project/
is outside from GOPATH tree. Whatever path I try to import from main.go
nothing works, the only case working fine is import "./internal/foo|bar"
. I think I do something wrong or get "internal" package idea wrong in general. Could anybody make things clearer, please?
UPDATE
The example above is correct the only what I need was to place project/
folder under $GOPATH/src
. So the thing is import path like the project/internal/foo|bar
is workable if we only import it from project/
subtree and not from the outside.
Best Answer
With modules introduction in Go v1.11 and above you don't have to specify your project path in $GOPATH/src
You need to tell Go about where each module located by creating go.mod file. Please refer to
go help mod
documentation.Here is an example of how to do it:
project/internal/bar/go.mod
project/internal/bar/bar.go
project/internal/foo/go.mod
project/internal/foo/foo.go
project/main.go
Now the most important module project/go.mod
Couple things here:
That is the reason why you need to have
replace
where you tell Go where to find it, and that is the key!Now, when you execute your code you will have
Here is GitHub link for this code example