How to Initialize a Go Module with go mod init

Cli
Run `go mod init` followed by your module's import path to create a new `go.mod` file, which tracks your project's dependencies and defines the module name.

Run go mod init followed by your module's import path to create a new go.mod file, which tracks your project's dependencies and defines the module name. This command initializes the module system for your project, allowing you to manage external packages using Go modules.

Use the full import path as the argument, typically matching your repository URL. For a local project or a new repository, you might use a placeholder domain or your actual Git hosting URL.

# Initialize a module with a specific import path
go mod init github.com/yourusername/myproject

# Initialize in the current directory with a relative path (less common for production)
go mod init ./myproject

After running the command, a go.mod file appears in your directory containing the module directive and the Go version. You can then add dependencies using go get, and Go will automatically update the go.mod and go.sum files. If you are working in a directory that already contains a go.mod file, go mod init will fail unless you use the -module flag to rename the existing module or delete the file first.

# Add a dependency (e.g., the "github.com/gin-gonic/gin" package)
go get github.com/gin-gonic/gin

# Verify the module structure
cat go.mod

The output of cat go.mod will look something like this:

module github.com/yourusername/myproject

go 1.21

require github.com/gin-gonic/gin v1.9.1

Ensure the module path matches the import path you use in your source code files. If you plan to host this code on GitHub, GitLab, or another platform, use the actual repository URL to avoid import errors for other developers. If you are working on a local experiment without a remote repository, a path like example.com/myproject is acceptable, but be aware that this will not resolve correctly for others unless you host the code at that specific URL.

If you need to change the module name later, simply edit the module line in go.mod manually or run go mod edit -module=new/path. Always run go mod tidy after making significant changes to dependencies to clean up unused entries and ensure the go.sum file is accurate. This keeps your dependency graph clean and reproducible.