Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 147 ยท Modules and Packages

Working with Third-Party Packages

Choose, add, upgrade and audit third-party Go packages - finding libraries, judging quality, go get, govulncheck, licenses, vendoring and popular libraries.

The Go standard library is large, and a surprising number of programs need nothing else. But sooner or later you want a router with richer features, a PostgreSQL driver, a command-line framework, or a library that reads a file format Go does not ship. Third-party packages are how the ecosystem shares that work, and each one you add is also code you did not write, review or control.

This lesson covers the whole life of a dependency: how to find candidates and judge their quality, how go get adds and upgrades them, how to keep them secure with govulncheck, what to check about licenses, when vendoring helps, and how to keep dependencies from taking over your design. It ends with a short tour of libraries that most Go developers meet sooner or later.

Go Modules explained the machinery behind go.mod, go.sum and version selection. Here we use that machinery. The sandbox on this site has no network access, so commands appear as read-only blocks; the runnable programs model the decisions (classifying imports, planning upgrades, checking advisories, isolating a vendor behind an interface).

Finding packages

The central place to search is pkg.go.dev, the official package index. It shows the documentation generated from each library's doc comments, the import path and version history, the license, the number of importers, whether the module is stable (v1 or above), and links to the repository. Search for a task ("postgres driver", "jwt"), and compare several results rather than taking the first.

Other ways to discover libraries: the "Awesome Go" lists on GitHub, the dependencies of well-regarded projects (open their go.mod), and golang.org/x/..., the repositories maintained by the Go team that sit outside the standard library's compatibility promise (x/sync, x/text, x/crypto, x/net, x/tools). The x packages are a good first stop when the standard library is almost enough.

Judging quality

A package that compiles is not necessarily one you want to depend on for years. Before adding a dependency, spend ten minutes on these checks:

  • Is it needed at all? Can 30 lines of your own code or a standard package do the job? A dependency is a permanent cost: updates, security reviews, API changes and extra build time.
  • Maintenance: recent commits and releases, responsive issue tracker, more than one maintainer. A library last touched four years ago may still be perfectly fine if it is small and finished, but a large one with unanswered security issues is a risk.
  • Stability: a v1.x module promises backward compatibility. v0.x means the API may change at any time, so expect work when upgrading.
  • Quality of the API: idiomatic Go uses interfaces from the standard library (io.Reader, context.Context, error), returns errors rather than panicking, and exposes a small surface. A package that defines its own Context type or logs globally will fight your code.
  • Dependencies of the dependency: go mod graph or go list -m all after trying it shows how many modules arrive with it. A package pulling in fifty transitive modules for a trivial task is a red flag.
  • Tests and documentation: examples in the documentation, a test suite, a changelog.
  • License: see below.
  • Popularity and adoption: many importers (pkg.go.dev shows the count) means more eyes on bugs, but it is not a replacement for the checks above.

Our first program inspects the imports of a source file and sorts them into the groups you should think about separately: standard library, your own module, the semi-official golang.org/x packages, and truly third-party code. This is the same logic go mod tidy and linters rely on, since a path whose first element has no dot is standard.

Go Classifying a file's imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Only two of the nine imports come from third parties, plus one from the x family. That is a healthy ratio; most of the file relies on the standard library.

Adding a dependency

Inside a module, the quickest way to add a package is to import it in your code and let the tooling fetch it:

Go
import "github.com/google/uuid"
Terminal
go mod tidy              # finds the missing module, adds it to go.mod and go.sum
# or, explicitly:
go get github.com/google/uuid
go get github.com/google/uuid@v1.6.0     # a specific version
go get github.com/google/uuid@latest     # the newest tagged release
go get github.com/google/uuid@main       # a branch (becomes a pseudo-version)
TEXT
go: downloading github.com/google/uuid v1.6.0
go: added github.com/google/uuid v1.6.0

go get changes the requirement in go.mod and downloads the code; go mod tidy reconciles go.mod with what your code imports. Commit both go.mod and go.sum. Removing a dependency is the reverse: delete the imports, run go mod tidy, and the requirement disappears. go get github.com/old/lib@none removes one explicitly.

Two details for newcomers:

  • go get also builds and installs commands in older versions of Go. Today it only manages dependencies. To install a tool (a program such as staticcheck), use go install honnef.co/go/tools/cmd/staticcheck@latest, or, since Go 1.24, declare it as a tool dependency in go.mod and run it with go tool staticcheck so the whole team uses the same version.
  • Only exported identifiers are available. If a library hides what you need, resist forking it or using unsafe hacks; open an issue first.

Keeping dependencies up to date

Dependencies need regular attention, not only when something breaks. See what is outdated:

Terminal
go list -m -u all
TEXT
github.com/go-chi/chi/v5 v5.1.0 [v5.2.1]
github.com/jackc/pgx/v5 v5.7.1 [v5.7.4]
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.0 [v1.8.1]

Square brackets show the newest available version. To upgrade:

Terminal
go get github.com/jackc/pgx/v5@latest   # one module
go get -u ./...                         # all dependencies of the packages here, to latest minor/patch
go get -u=patch ./...                   # only patch releases (safest)
go mod tidy
go test ./...

Because of minimal version selection, upgrading is always something you ask for. A fresh build never picks up a newer release by surprise, and go.sum verifies what you got. Your tests are the safety net: upgrade, run them, read the release notes for anything that matters, then commit.

Semantic versioning tells you how careful to be. This program classifies available updates the way a human would triage them:

Go Planning upgrades from version numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For a major version, remember that the import path itself changes (/v2), so moving to it means editing imports across your code, usually with a find-and-replace and some compile-error fixing. You can often keep v1 for a long time, and run both versions side by side during a gradual migration.

Not every v0.x release is a mistake: many excellent libraries stay below v1 for years. Just plan to read the changelog before you update them.

Security: govulncheck

Dependencies have bugs, and some of those are security vulnerabilities. The Go team runs a public vulnerability database (vuln.go.dev) and provides a tool that checks your project against it:

Terminal
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
TEXT
Vulnerability #1: GO-2025-0001
    Denial of service in example.com/yamlish
  More info: https://pkg.go.dev/vuln/GO-2025-0001
  Module: example.com/yamlish
    Found in: example.com/[email protected]
    Fixed in: example.com/[email protected]
    Example traces found:
      #1: internal/config/load.go:41:22: config.Load calls yamlish.Decode

Your code is affected by 1 vulnerability from 1 module.
This scan also found 0 vulnerabilities in packages you import and 1
vulnerability in modules you require, but your code doesn't call these
vulnerabilities.

(That output is an invented illustration of the format; run the tool on your machine for real results.) What makes govulncheck more useful than plain version matching is that it analyzes which functions your code actually calls. A vulnerability in a package you require but never reach is reported as lower priority, so you are not buried in noise. The fix is usually go get module@fixedVersion followed by go mod tidy; the tool prints the fixed version.

The following program models the decision logic with made-up advisories and modules: compare the version you require with the first fixed version, and note whether the vulnerable function is actually used:

Go Checking dependencies against advisories (simulated)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Run govulncheck in continuous integration, on a schedule and before releases, since advisories appear after you ship. Also enable automated update tools such as Dependabot or Renovate, which open pull requests for new versions.

Supply-chain safety is more than known vulnerabilities. Prefer popular, maintained modules; read the code of small dependencies you rely on for something sensitive; watch for look-alike package names (github.com/gorilla/mux versus a similar-looking copy); and keep go.sum under version control. The checksum database makes sure you get the same bytes everyone else got, but not that those bytes are good.

Licenses

Every package comes with a license, and your project inherits obligations from it. Permissive licenses (MIT, BSD-2/3-Clause, Apache-2.0, ISC) are common in the Go ecosystem and mostly require keeping the copyright notice. Copyleft licenses (GPL, AGPL, and to a lesser extent LGPL and MPL) can require you to publish your own source under the same terms when you distribute software that includes them; for a company shipping a closed-source product, that matters a great deal. A package with no license at all is not free to use, no matter where it is hosted.

pkg.go.dev lists the license of each module, and tools such as github.com/google/go-licenses report licenses for every dependency of your project and can fail a build when a forbidden one appears. For a commercial or commercial-adjacent project, agree on an allow-list early, because replacing a dependency late is expensive. (This is general information, not legal advice; ask a lawyer when it counts.)

Vendoring

go mod vendor copies the source of all dependencies into a vendor/ directory and writes vendor/modules.txt. With a vendor/ directory present, builds use it automatically.

Terminal
go mod vendor
go build ./...             # uses ./vendor
go mod verify              # checks the module cache against go.sum
go build -mod=mod ./...    # ignore vendor/, use the module cache

Vendoring helps when you need builds without network access, when you want dependency changes to appear in code review as ordinary diffs, or when your company wants a copy under its own control. The costs are a bigger repository and merge noise. Many teams skip it because the module proxy keeps versions available and go.sum guarantees integrity. If you do vendor, run go mod vendor in CI and fail the build if git diff vendor/ is not empty, so the directory can never silently fall out of sync with go.mod.

Keep dependencies at arm's length

The best way to live with third-party code is to make sure only a small part of your program knows it exists. Go's implicit interfaces make this easy: define the small interface your application needs, write an adapter that wraps the vendor's types, and let everything else depend on your interface. Swapping the library, or faking it in a test, then touches one file. It also protects you from API changes in the library.

Go An adapter between your code and a vendor SDK

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

welcome depends only on Mailer. In production you pass the adapter; in a test you pass the fake and inspect sent. If the vendor renames Deliver next year, only vendorMailer.Send changes. This is the "accept interfaces, return structs" advice from Designing with Interfaces applied to dependency management. Don't over-apply it: wrapping a stable, tiny, ubiquitous library (such as uuid) in your own interface often adds ceremony without benefit.

The standard library goes a long way

Modern Go absorbed many things that used to need a package. Before adding a dependency, check whether the standard library covers it:

Go Standard library instead of helper packages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In a handful of lines the standard library gave us sorted map keys, multi-key sorting, searching, combined errors, structured logging (log/slog has replaced most use of logging frameworks) and a first-non-zero-value default with cmp.Or. Since Go 1.22 the net/http router also handles methods and path parameters, which retired a big reason for routers like gorilla/mux. Check the standard library first; reach for a package when it clearly earns its place.

You will see these names again and again. All are well maintained at the time of writing, but always check the current state before you adopt one.

Library Import path What it is for
chi github.com/go-chi/chi/v5 A small router and middleware set that works with net/http handlers
cobra github.com/spf13/cobra Command-line apps with subcommands, flags and help (used by kubectl, Hugo)
pgx github.com/jackc/pgx/v5 The most widely used PostgreSQL driver and toolkit
sqlc github.com/sqlc-dev/sqlc Generates type-safe Go from SQL queries (a code generator, run as a tool)
testify github.com/stretchr/testify Assertions (assert, require) and mocks for tests
uuid github.com/google/uuid UUID generation and parsing
viper github.com/spf13/viper Configuration from files, environment and flags
zap, zerolog go.uber.org/zap, github.com/rs/zerolog Fast structured loggers (often replaced today by log/slog)
websocket github.com/coder/websocket, github.com/gorilla/websocket WebSocket servers and clients
x/sync golang.org/x/sync errgroup, singleflight, semaphore
x/crypto golang.org/x/crypto bcrypt, argon2, ssh and more

Notice the spread: some replace what the standard library does less conveniently (testify, chi), some add what it lacks (pgx, websocket), and some are tools you run rather than link (sqlc). Later lessons use several of them: SQL in Go covers sqlc and migrations, Building an HTTP Server shows how far net/http goes alone, and Testing with the testing Package explains when the plain testing package is enough.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run go get -u=patch ./.... What does it upgrade?

    The patch form of -u moves each dependency to the latest patch release of the minor version it already uses, the safest kind of upgrade.
  2. 2. A dependency released v3.0.0 while you use v2.4.1. Why is switching not just a version bump in go.mod?

    Semantic import versioning puts the major version in the import path. You edit the imports and fix any breaking API changes.
  3. 3. What advantage does govulncheck have over comparing version numbers with a list of advisories?

    govulncheck analyses which functions your code reaches, so it can tell a reachable vulnerability from one in code that is never called.
  4. 4. Which design keeps a third-party SDK from spreading through your whole program?

    An adapter behind your own interface confines the dependency to one file, makes tests easy with fakes and limits the impact of API changes.
  5. 5. Which statement about licenses is correct?

    Without a license you have no permission to use the code. Copyleft licenses can require you to share your own source under the same terms when you distribute.

Summary

  • Search pkg.go.dev, then judge a candidate on need, maintenance, stability (v1+), API quality, its own dependencies, tests and license before you add it.
  • go get module@version changes requirements, go mod tidy reconciles go.mod and go.sum with your imports; commit both files.
  • go list -m -u all shows available updates; go get -u=patch ./... is the safest bulk upgrade, and a new major version means changing the import path.
  • Run govulncheck ./... regularly; it focuses on vulnerable functions your code actually reaches. Pair it with automated update pull requests.
  • Check licenses (permissive versus copyleft versus none) before depending on a package in a product.
  • Vendoring (go mod vendor) gives offline, reviewable builds at the cost of repository size; most projects rely on the proxy and go.sum.
  • Keep third-party code at the edges behind small interfaces, and use the standard library (slices, maps, cmp, slog, errors.Join, the 1.22 ServeMux) before adding a package.

Next: Testing with the testing Package