Skip to content

Useful Go Stuff

Update direct dependencies only

Updates all direct dependencies of the current Go module to their latest versions.

go get $(go list -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' -m all)

This can be used instead of go get -u ./..., which updates all dependencies, including transitive dependencies. The latter may not always be desirable.

Update all dependencies

Checks for and applies all available updates to module's dependencies.

go list -u -m all | grep '\[' | awk '{print $1}' | xargs -n1 go get -u

Get specific dependency version from go.mod

go list -m -json github.com/pressly/goose/v3 | jq -r .Version

List latest stable version regardless of go.mod

go list -m -versions github.com/pressly/goose/v3 | tr ' ' '\n' | sort -V | grep -v '-' | tail -n 1

The sort -V command is a version of the sort utility that performs version number sorting. It understands the logical order of version numbers, which may not always correspond to alphabetical or numerical order.

Example:

1.10
1.2
1.1
2.0
1.11

Regular sort:

1.1
1.10
1.11
1.2
2.0

But sort -V would correctly order them as:

1.1
1.2
1.10
1.11
2.0

This is because sort -V understands that in version numbers, 1.2 comes before 1.10.

Explain dependencies

# Lists all module dependencies (excluding the main module) by skipping the first line.
# For each dependency, explains why it's needed in the module.
go mod why -m $(go list -m all | tail -n +2)

This can be particularly useful when:

  • Auditing dependencies
  • Trying to reduce the size of the module
  • Understanding the dependency tree

Identify which direct dependencies are pulling in various indirect dependencies.