malformed module path "xxxx/xxxx/uuid" missing dot in first path element when migrating from GOPATH based dep to go mod

Ayush Gupta picture Ayush Gupta · Oct 20, 2019 · Viewed 19.7k times · Source
$ go version
1.13.3

I have a folder structure as follows:

GOPATH
+---src
     +--- my-api-server
           +--- my-auth-server
                 +--- main.go
           +--- my-utils
                 +--- uuid
                       +--- uuid.go

my-auth-server uses my-api-server/my-utils/uuid as a depenency

Now, when I used the GOPATH based module system, this worked fine. But when using go modules, when I run go run main.go in my-auth-server it returned error:

build command-line-arguments: cannot load my-api-server/my-utils/uuid: malformed module path "my-api-server/my-utils/uuid": missing dot in first path element

Any idea how to solve this?

Answer

Tyler Bui-Palsulich picture Tyler Bui-Palsulich · Oct 25, 2019

The go.mod file should be at the root of your project (in this case, my-api-server/go.mod).

The first part of the module path should be a domain/path. For example, the full path might be github.com/your-github-username/my-api-server. The error you're seeing is because the first part is not a domain (with a period). You don't have to publish the module to develop it, but you need to use a proper domain name.

Once you have a module path, you can import packages contained in that module using the full module path + "/" + the relative path of the package. For example,

import "github.com/your-github-username/my-api-server/my-utils/uuid"

Since main.go and uuid are contained in the same module, you don't need a require statement in the go.mod file to use the uuid package. You can import it like any other package and it will work.

I recommend using go build and running the resulting executable rather than using go run to make sure you include all of the files you need in the build process.

See https://blog.golang.org/using-go-modules for a walkthrough of how to use Go modules, including the second post in that series about how to convert a project to use modules.