Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

Go get cannot find local packages when using multiple modules in a repo

I'm having issues with go's new module system, as I'd like to define a local module and import it in the main program. The local package resides in a folder of the main package/root folder. Imagine the following project structure outside the $GOPATH.

Project structure

./main.go

package main

import "fmt"
import "example.com/localModule/model"

func main() {
    var p = model.Person{name: "Dieter", age:25}
    fmt.Printf("Hello %s
", p.name)
}

./model/person.go

package model

type Person struct {
    name string
    age int
}

In the root folder I initialized a module by calling

go mod init example.com/localModule

In the model/ folder I then initialized the submodule by calling

go mod init example.com/localModule/model

The error

In the root folder calling the following commands fail.

$ go get
go build example.com/localModule/model: no Go files in

$ go build
main.go:4:8: unknown import path "example.com/localModule/model": cannot find module providing package example.com/localModule/model

The error message for go get is cut off, I din't parse it wrongly.

I do not plan on pushing the module to a server and and just needed a way of referencing the local package model, so I chose example.com/localModule/ and example.com/localModule/model respectively.

I'm using go1.11 darwin/amd64 on a Macbook running MacOS 10.13.6.

question from:https://stackoverflow.com/questions/52079662/go-get-cannot-find-local-packages-when-using-multiple-modules-in-a-repo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can have local "sub" modules like you ask for by adding a require statement and a matching replace statement with a relative file path in go.mod.

In the "root" ./go.mod:

module example.com/localModule

require example.com/localModule/model v0.0.0

replace example.com/localModule/model v0.0.0 => ./model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...