Getting Started with Go Modules
Go modules have become the standard way to manage dependencies in Go projects. In this post, we will walk through the basics of setting up and using Go modules.
Initializing a Module
To start a new Go module, run:
go mod init github.com/username/project
This creates a go.mod file that tracks your dependencies.
Adding Dependencies
Simply import a package in your code and run:
go mod tidy
Go will automatically download and add the dependency to your go.mod file.
Versioning
Go modules use semantic versioning. You can specify version requirements in your go.mod:
require (
github.com/gin-gonic/gin v1.9.1
github.com/lib/pq v1.10.9
)
Tips
- Use
go mod vendorif you want to vendor dependencies - Run
go mod verifyto check dependency integrity - Use
go list -m allto see all dependencies
That is all for this quick overview. Go modules make dependency management straightforward and reproducible.