Use go get to download and add a package to your module's go.mod file, but prefer go get only for adding new dependencies or updating specific versions, as go mod tidy is the standard for cleaning up unused imports. Running go get fetches the package and its dependencies, updating go.mod and go.sum automatically.
Here is how to add a new dependency, such as the github.com/gin-gonic/gin web framework:
go get github.com/gin-gonic/gin
If you need a specific version or the latest version of a package that has already been added, you can specify the version tag directly:
go get github.com/gin-gonic/gin@v1.9.1
After adding dependencies, always run go mod tidy to ensure your go.mod file is clean and only contains packages actually used in your code. This command removes unused dependencies and adds any missing ones based on your imports.
go mod tidy
Note that go get behaves differently depending on whether you are inside a module. If you are outside a module directory, it downloads the package to your GOPATH but does not create a go.mod file. Inside a module, it updates the module files directly. Avoid using go get to upgrade all dependencies at once; instead, use go get -u with caution or rely on go mod tidy combined with specific version updates to maintain stability.
If you encounter issues where the package isn't found, ensure the import path is correct and that the repository is accessible. For private repositories, you may need to configure authentication via environment variables or a .netrc file before running go get.
In modern Go workflows, go get is primarily a tool for managing the dependency list, while the actual compilation and linking are handled by go build or go run. Always verify that your go.mod reflects the intended versions after running go get by checking the file manually or using go list -m all.