go modules installing go tools

Luis.at.code picture Luis.at.code · Nov 19, 2018 · Viewed 26.6k times · Source

I'm using go modules as dependency management, and I'm having problem to install something like this:

go get -u github.com/go-critic/go-critic/...

the result from above was:

go: cannot find main module; see 'go help modules'

Answer

typical182 picture typical182 · Aug 2, 2019

Several of the other answers here have grown stale at this point.

There are at least two cases to consider:

Case 1

You want to install a tool, but you don't want to modify your current go.mod to track that tool as a dependency.

In short, with Go 1.12 or 1.13, the simplest solution is to cd to a directory without a go.mod, such as:

$ cd /tmp
$ go get github.com/some/[email protected]

Alternatively, gobin is a module-aware command to install or run binaries that provides additional flexibility, including the ability to install without altering your current module's go.mod

See this related answer for more details, including a solution for Go 1.11, as well as the likely new option in Go 1.14 for getting a tool without it updating your go.mod.

Case 2

On the other hand, if you want to explicitly track a tool as a versioned dependency in your go.mod, then see the "How can I track tool dependencies for a module?" FAQ on the modules wiki.

In short, you create a tools.go file in a separate package, and set a // +build tools build tag, such as:

// +build tools

package tools

import (
    _ "golang.org/x/tools/cmd/stringer"
)

The import statements allow the go command to precisely record the version information for your tools in your module's go.mod, while the // +build tools build constraint prevents your normal builds from actually importing your tools.