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

Tobs.Core picture Tobs.Core · Aug 29, 2018 · Viewed 32k times · Source

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\n", 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.

Answer

Jostein Stuhaug picture Jostein Stuhaug · Sep 12, 2018

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