Root of the Issue
It turns out this issue has nothing to do with Go modules. It is raised because importing from internal
folders is disallowed in Go if you aren't in the same tree.
How to Solve It
The only way to fix this issue is to not use an import statement to the source's internal
folder, but instead replace it with an import statement to the fork's.
If you've already used a replace
directive the way OP has, you do not need to change any other import statement - just the one that's giving you trouble.
Walkthrough of the Solution
Suppose you have source github.com/source/s
and you have made a fork github.com/fork/f
, and you've cloned the fork locally before making changes.
The go.mod
for the fork will look like
module github.com/source/s
go 1.11
require (
...
)
and assume the file that's throwing the internal
error will look like
package main
import (
"github.com/source/s/something"
"github.com/source/s/internal/somethingelse"
)
...
Add a replace
directive and change the module
directive to mirror your fork:
module github.com/fork/f
go 1.11
replace github.com/source/s => github.com/fork/f
require (
...
)
Now run go clean -modcache
(to clear any older modules already imported by this module) and run go mod tidy
. This gets everything installed cleanly, which removes any other sources of possible issues.
Go to the folder containing the problematic file, and run go install
(as the OP did). You will see an error:
main.go: use of internal package source/s/internal/somethingelse not allowed
Just replace the problematic file's contents with:
package main
import (
"github.com/source/s/something"
"github.com/fork/f/internal/somethingelse"
)
...
and rerun go clean -modcache
and go mod tidy
.
Now you should be able to run go install
with no issues, and have replace
work the way you want.
(Personally, this was a very frustrating issue for me to solve! I was working on modifying a fork of a core package in the Go ecosystem, and the sheer number of dependencies that would break if you tried changing import paths naively made me tear my hair out. I am now able to sleep peacefully at night knowing the answer to this question.)