Lesson 3: Working with External Packages in Go
In this lesson, you will learn how to leverage third-party libraries to enhance your Go projects and extend functionality beyond the standard library.
In the previous lessons, you learned Go fundamentals and how to work with REST APIs using only the standard library.
Now it's time to expand your toolkit by learning how to leverage external packages from the Go community.
In this lesson, you will learn how to leverage third-party packages to enhance your Go projects, manage dependencies with Go modules, install and use external packages like fatih/color for terminal styling, and discover popular CLI frameworks that will elevate your command-line applications.
What You'll Learn
- Understanding the three types of packages in Go (standard library, external, and local).
- Using
go modto manage project dependencies. - Installing and importing external packages with
go get. - Working with the popular
fatih/colorpackage for terminal styling. - Exploring useful CLI packages like Cobra, urfave/cli, and Kingpin.
- Best practices for dependency management in Go projects.
Introduction
Working with packages in Go is essential, as almost everything you need to do requires a package.
For example, to print a message to the screen, you use the fmt package, which includes the functions necessary to print to the screen.
In Lessons 1 and 2, you've already been using packages from Go's standard library, such as fmt, net/http, encoding/json, io, and log, which are built into Go and available immediately, but what if you need functionality that doesn't exist in the standard library?
Packages in Go are divided into three parts or categories.
1. Standard Library Packages
The first is the standard library, which contains packages maintained by the Go team, where you do not need to download them, as they are part of the language and already available for you to use directly; you just need to import them.
Examples you've already used:
fmt- formatting and printing/net/http- HTTP client and server.encoding/json- JSON encoding/decoding.io- input/output operations.log- logging.
2. External (Third-Party) Packages
The second type of packages are the external ones, which are not part of the standard library and are not maintained by the Go team.
These are community packages developed and maintained by the community, often called third-party packages.
You can also be one of them if you write a package that may help other Go developers; you can share it, and others can use it as an external package.
External packages are not available by default, so you need to download them first, and this is done using go get, which is a tool that adds the downloaded package to your Go project, and these packages are usually hosted on GitHub and GitLab.
3. Local Packages
The third type is local packages, which are packages that you develop yourself and use inside your project to organize code and improve maintainability.