This article will overview five packages in the Go ecosystem that Go developers can use to build their applications faster.
- The UUID package for generating universally random identifiers
- The Cobra-Cli package for building command line apps
- The Tesify Package for Easier Testing
- The Zap Package by Uber for structured logging
- The Gonum Package for Scientific Computing
Go is a statically typed compiled language that has gained popularity for its simplicity, efficiency, and support for concurrency. One of the features contributing to Go’s efficiency is the standard library and third-party packages.
In Go, packages are collections of related Go source file to be compiled together. Packages enhance code reusability and are the basis for Go’s modularity and separation of concerns which is useful for code maintenance and testing.
This article will delve into Go packages that you can use to develop applications faster for increased productivity. These packages for popularly used by Go developers to build a real-world application
The UUID Package
The gouuid package is a Go package that provides a simple, straightforward interface for generating universally unique identifiers (UUIDs). UUIDs are a standardized way of generating globally unique IDs that you can use across various resources, from filenames to database records.
One of the main features of the package is the functionality of generating various types of UUIDs from version 1 (time-based) to version 4 (random) and version 5 (named). The package also provides functions for parsing and validating UUIDs, including generating and comparing UUIDs in a secure, cryptographic way.
Additionally, the gouuid package supports generating and parsing other types of universally unique identifiers, from GUIDs (Globally Unique Identifiers) to ULIDs (Universally Unique Lexicographically Sortable Identifiers).
Run this command in the terminal of your project’s directory to install the gouuid package.
go get github.com/nu7hatch/gouuid
Once you have installed the gouuid package, you can import the package for your program by specifying the installation path.
import ( "fmt" "github.com/nu7hatch/gouuid" )
Next, generate a version four UUID with the gouuid package.
func main() { // Generate a new UUID. id, err := uuid.NewV4() if err != nil { fmt.Println(err) return } // Print the UUID. fmt.Println(id) }
The main function is the program’s entry point, which generates and prints the UUID using the NewV4 method of the uuid package.
The NewV4 method returns the UUID and an error for handling.
The Cobra-Cli Package
The Cobra package is a feature-rich package for building powerful, easy-to-use CLI applications. You can harness the Cobra package to build various command line interfaces, from simple to complex ones, with various flags, arguments, and features. Cobra is an excellent choice for building CLIs for its simplicity and flexibility. The package also provides a straightforward set of functions and data structures for defining commands and flags that can be extended.
Additionally, Cobra automatically generates a helpful usage message and a flag parsing function, saving you the time and effort of implementing these features yourself.
Run this command in the terminal of your project’s directory to install the cobra package.
go get github.com/spf13/cobra
Once you have installed the package, you can import the package for your program by specifying the installation path.
import ( "fmt" "os" "github.com/spf13/cobra" )
Finally, you can set up a command that prints with the cobra package.
func main() { var cmdPrint = &cobra.Command{ Use: "print [string to print]", Short: "Print anything to the screen", Long: `print is for printing anything back to the screen. For many years people have printed back to the screen.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + args[0]) }, } var rootCmd = &cobra.Command{Use: "app"} rootCmd.AddCommand(cmdPrint) rootCmd.Execute() }
The code defines a CLI app using the Cobra package. The app has a single command (the print command) that accepts a string argument that’s output to the console.
On running the app, you can type the command app print hello to print the “hello” string to the console.
The Testify Package
The testify package is one of the popular choices for testing and assertions in Go. The package provides functions for writing robust tests and assertions based on code behavior.
The package features are the assertion functions, mock object generation, subtests, and table-driven tests.
Generally, the testify package is a powerful tool for testing and assertions in Go, and testifywidely used in the Go community for writing reliable and maintainable tests; hence, the package is an essential part of any Go developer’s toolkit.
Run this command in the terminal of your project’s directory to install the testify package.
go get github.com/stretchr/testify
After installing the testify package, you can import the package for your program by specifying the installation path.
import ( "testing" "github.com/stretchr/testify/assert" )
Here’s an example of testing and assertions with the testify package.
func Add(int1, int2 int) int { a := int1 b := int2 sum := a + b return sum } // TestAdd should be in a test file func TestAdd(t *testing.T) { // Test normal case result := Add(1, 2) assert.Equal(t, 3, result) // Test edge case result = Add(0, 0) assert.Equal(t, 0, result) }
The code above defines a test function for a Go program. The TestAdd function tests an Add function using the Equal method of the testify package for the expected result.
You can run your test using the test command of the go command. Adding a -v flag returns a verbose output.
go test -v
The Zap Package
The zap package is a high-performance logging library for Go applications. The zap package provides fast, structured logging for Go apps, customizable log levels, automatic contextual information, and extensibility.
Run this command in the terminal of your project’s working directory to install the zap package.
go get go.uber.org/zap
Here’s how you can import the zap package in your Go file.
import ( "go.uber.org/zap" )
Here’s an example of logging using the zap package’s functions.
func main() { logger, err := zap.NewProduction() if err != nil { panic(err) } defer logger.Sync() logger.Info("Starting the application...") // some code here logger.Error("An error occurred!") }
You created a logger instance with the NewProduction method of the zap package that creates a fully configured logger optimized for production environments. if there are errors, the error gets returned.
The defer statement at the end of the block tells the program to run the Sync method on the logger when the function completes. Thus flushing any buffered log entries to the log output destinations.
The Info and Error methods log messages at different levels. The Info method logs an informational message, while the Error method logs an error message.
Finally, the program logs another message with the Error method, indicating that an error has occurred during the execution of the program.
The Gonum Package
Gonum is an open-source numerical library for Go that provides various numerical functions, from linear algebra to probability distributions and optimization algorithms.
Gonum provides a comprehensive set of linear algebra functions, including matrices, vectors, factorizations and decompositions, probability distributions for statistical distributions from normal to binomial and poissons. It also provides optimization routines for the maximum and minimum functions, including gradient descent and newtons method.
Run this command in your project’s terminal to install the Gonum package.
go get gonum.org/v1/gonum/mat
Then, import the gonum package after a successful installation process. Here’s an importation of the mat package for matrix operations.
import ( "fmt" "gonum.org/v1/gonum/mat" )
Here’s an array of operations you can carry out with the mat package for matrices.
func main() { // Create a new matrix with 2 rows and three columns. matrix := mat.NewDense(2, 3, []float64{1, 2, 3, 4, 5, 6}) // Get the number of rows and columns. rows, cols := matrix.Dims() fmt.Printf("Matrix has %d rows and %d columns\\n", rows, cols) // Get and set the value at a particular location. val := matrix.At(0, 0) fmt.Printf("Value at (0, 0) is %.2f\\n", val) matrix.Set(0, 0, 99) }
The program demonstrates how you can use the mat package from the gonum package to perform various operations on matrices.
The mat.NewDense function creates a new matrix with the specified number of rows and columns and a slice of float64 values for the matrix initialization.
The Dims function returns the number of rows and columns in the matrix. The At function returns the value at a particular location in the matrix, and the Set function sets the value at a particular location in the matrix.
Conclusion
You’ve learned about the gouuid, testify, gonum, zap, and cobra packages. You’ve also learned about the package’s functionality, how they help you build apps faster, and how you can get started with the packages.
Third-party packages are handy for speeding up development and reducing the amount of code to be written since they provide pre-built solutions to common problems, allowing developers to focus on the unique aspect of their projects.