I would recommend becoming familiar with go mod tidy
. The help text from go itself is more informative than my transcription would be:
$ go help mod tidy
usage: go mod tidy [-e] [-v] [-x] [-diff] [-go=version] [-compat=version]
Tidy makes sure go.mod matches the source code in the module.
It adds any missing modules necessary to build the current module's
packages and dependencies, and it removes unused modules that
don't provide any relevant packages. It also adds any missing entries
to go.sum and removes any unnecessary ones.
...
SRC: https://go.dev/src/cmd/go/internal/modcmd/tidy.go
(archive.org mirror)