I have a project that looks like this:
mymodule
- mypackage1
-- generate.go # Generates documentation from models.go
- mypackage2
-- models.go # Defines structs
- go.mod # First line "module github.com/mymodule"
- go.sum
In mypackage1/generate.go
, I want to import and document the structs defined in mypackage2/models.go
. To do that, I tried executing this code in mypackage1/generate.go
, modified from here and here:
_ = mypackage2.Mytype{}
pkg, err := importer.Default().Import("example.com/mymodule/mypackage2")
if err != nil {
fmt.Println("error:", err)
}
for _, declName := range pkg.Scope().Names() {
fmt.Println(declName)
}
mypackage2
is successfully imported and the first line of this block compiles without problem. But the call to importer
fails and prints this error:
error: can't find import: "example.com/mymodule/mypackage2"
The import does work for fmt
, but not for github.com/gorilla/mux
. Does anyone have an idea what might be going wrong?
This question (How to use go importer ) is the most relevant, but I get the same error following these instructions for github.com/gorilla/mux
(a dependency of my package).
This question explains to use the module name defined in go.mod
, but I already do that. Neither that nor the mypackage2
standalone name works.
This question is related but uses a deprecated API and has no answer.