I have the following files :
$GOPATH/src/example.com
├── a
│ ├── a.go
│ └── go.mod
├── b
│ ├── b.go
│ └── go.mod
└── c
├── go.mod
└── main.go
Contents are :
a/a.go
:
package a
func NewA() int {
return 1
}
a/go.mod
:
module example.com/a
go 1.17
b/b.go
:
package b
import A "example.com/a"
func NewB() int {
return A.NewA()
}
b/go.mod
:
module example.com/b
go 1.17
replace example.com/a => ../a
require example.com/a v0.0.0-00010101000000-000000000000 // indirect
c/main.go
:
package main
import "fmt"
import B "example.com/b"
func main() {
fmt.Println(B.NewB())
}
c/go.mod
:
module example.com/c
go 1.17
replace example.com/b => ../b
require example.com/b v0.0.0-00010101000000-000000000000 // indirect
Then when I type in the c
directory : go run main.go
I get :
../b/b.go:3:8: missing go.sum entry for module providing package example.com/a (imported by example.com/b); to add:
go get example.com/b@v0.0.0-00010101000000-000000000000
And go get example.com/[email protected]
says :
go: downloading example.com/a v0.0.0-00010101000000-000000000000
example.com/b imports
example.com/a: unrecognized import path "example.com/a": reading https://example.com/a?go-get=1: 404 Not Found
For sure this is a local package and not available on internet and it's written in all mod files with replace
.
How to work with local packages ?
If I rename example.com
to example
I get : missing dot in first path element
.
CodePudding user response:
Quoting from Go Modules Reference: replace
directive:
replace
directives only apply in the main module’sgo.mod
file and are ignored in other modules. See Minimal version selection for details.
The replace
directive in b/go.mod
has no effect when you build the main package / module. You must add that replace
directive to the main module's go.mod
.
So add it to c/go.mod
. After running go mod tidy
in the c
folder, it'll look like this:
module example.com/c
go 1.17
replace example.com/b => ../b
replace example.com/a => ../a
require example.com/b v0.0.0-00010101000000-000000000000
require example.com/a v0.0.0-00010101000000-000000000000 // indirect
Without this replace
in c/go.mod
you were seeing the error message because the go tool tried to get the package from example.com
(which is an existing domain) but it does not contain a go module.