Skip to content

/commands/go/go-mod-init

go mod init: create a Go module (go.mod)

The commands on this page have not been executed by our verification runner yet.updated
tool
Go
versions
Go 1.16+ (modules on by default)
os
any

go mod init example.com/hello creates a go.mod file in the current directory, which makes that directory the root of a Go module named example.com/hello. The argument is the module path: the import prefix for the module's packages, and normally the repository location (github.com/USER/REPO) if you plan to publish it. Run it once per project, then go mod tidy to record dependencies.

Create a module

bash
mkdir hello && cd hello
go mod init example.com/hello

The new go.mod contains the module path and a go directive with the Go version of the toolchain that created it:

go.mod
module example.com/hello

go 1.NN

(1.NN stands for your installed Go version.)

Add dependencies

bash
# write code that imports a package, then:
go mod tidy          # adds missing requirements to go.mod and go.sum, removes unused ones
go get example.com/pkg@v1.2.3   # add or change one dependency explicitly

go.sum holds checksums of the dependency versions. Commit both go.mod and go.sum.

Choosing the module path

ProjectModule path
Will be published on GitHubgithub.com/USER/REPO
Private repositoryThe repository URL without the scheme, e.g. git.example.com/team/app
Local experiment, never imported by othersAny name, e.g. example/hello
Major version 2 or laterPath ends in /v2, /v3 ... (e.g. github.com/USER/REPO/v2)

Common errors

  • go: cannot determine module path for source directory ... (outside GOPATH, module path must be specified): run go mod init with an explicit module path.
  • go: ... go.mod already exists: the directory is already a module; edit go.mod (or use go mod edit -module NEW_PATH) instead.

Sources