The Ultimate Guide to the Most Useful Go Packages

It’s better to reuse whatever is already built, rather than building from scratch...
May 4 2023 · 10 min read

Background

Developing software in Go can be an incredibly powerful and efficient experience, but with so many packages(libraries) available, it can be overwhelming to find the right ones for your needs. Going through each package one by one to identify the most useful can be cumbersome, and ultimately reduce your productivity.

That’s why we’ve put together this ultimate guide to the most useful Go packages.

Of course, this guide is based on our own opinions, and there may be other libraries out there that are equally useful but didn’t make the cut. That’s why we invite you to share your own recommendations in the comments section below.

So whether you’re a seasoned Go developer looking to streamline your workflow, this guide is for you. Without further ado, let’s dive into the world of Go Packages and see what’s out there!


Sponsored

We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!


Database Packages

go-grm/gorm

  • GORM is a popular ORM package for Go that aims to simplify database operations by providing a high-level, expressive API.
  • GORM supports a wide range of databases, including MySQL, PostgreSQL, SQLite, and SQL Server, and allows you to perform common database operations such as querying, inserting, updating, and deleting records using Go structs.

Example

package main

import "github.com/go-gorm/gorm"

type User struct {
  ID   uint
  Name string
}

func main() {
  db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8mb4&parseTime=True&loc=Local")
  if err != nil {
    panic(err)
  }
  defer db.Close()

  var user User
  db.Where("name = ?", "John").First(&user)
}

Benefits

  • It allows you to write database queries using Go syntax, which makes the code more readable and maintainable.
  • It provides powerful features such as database migrations, transaction support, and query caching that can help simplify your code and improve performance.

Visit Golang: gorm with MySQL and gin for full implementation reference.


go-sql-driver/mysql

  • It is a MySQL driver for Go’s database/sql package. It provides a native Go implementation of the MySQL protocol and allows Go programs to communicate with a MySQL database server.

Example

Here is an example of how to use go-sql-driver/mysql to connect to a MySQL database and execute a query:

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // Open a connection to the database
    db, err := sql.Open("mysql", "user:password@tcp(host:port)/database")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    // Execute a query
    rows, err := db.Query("SELECT * FROM users")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer rows.Close()

    // Process the results
    for rows.Next() {
        var id int
        var name string
        var email string
        err = rows.Scan(&id, &name, &email)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("ID: %d, Name: %s, Email: %s\n", id, name, email)
    }
}

Benefits

  • Supports a wide range of MySQL features, including prepared statements, transactions, and SSL encryption.
  • Supports connection pooling, allowing for efficient management of database connections.

jmoiron/sqlx

It is an extension to the standard Go SQL driver that provides a set of useful utilities for working with SQL databases. It provides a lightweight SQL database access layer on top of Go’s built-in database/sql package, allowing you to easily execute queries and map the results to Go structs.

Example

import (
    "database/sql"
    "github.com/jmoiron/sqlx"
)

type User struct {
    ID   int    `db:"id"`
    Name string `db:"name"`
    Age  int    `db:"age"`
}

func getUser(db *sqlx.DB, id int) (User, error) {
    var user User
    err := db.Get(&user, "SELECT * FROM users WHERE id = ?", id)
    if err != nil {
        return User{}, err
    }
    return user, nil
}

Benefits

  • The main benefits of sqlx over the standard database/sql package is the ability to work with result sets more easily.
  • It uses named queries. These are the queries, defined using a name rather than being defined inline in the code. This allows us to separate the SQL code from the Go code, making it easier to maintain and modify the queries.

Note

  • If you use Gorm, it handles all the things under the hood and doesn’t need any other packages.
  • If you use database/sql, then jmoiron/sqlx OR go-sql-drivercan make your life easy while using it!

Authentication & Authorization Packages

dgrijalva/jwt-go

It is used for creating and verifying JSON Web Tokens (JWTs) in Go. JWTs are a popular method of authentication and authorization in web applications.

Example

The below snippet generates the JWT token using the provided custom claims.

package main

import (
 "fmt"
 "time"

 "github.com/dgrijalva/jwt-go"
)

func main() {
 // Define the token claims
 claims := jwt.MapClaims{
  "username": "johndoe",
  "exp":      time.Now().Add(time.Hour * 24).Unix(),
 }

 // Create the token object with the claims
 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

 // Generate the signed token string
 tokenString, err := token.SignedString([]byte("secret"))
 if err != nil {
  fmt.Println("Error generating token:", err)
  return
 }

 // Print the generated token string
 fmt.Println("Generated token:", tokenString)
}

Benefits

  • Provides a simple and easy-to-use interface for creating and verifying JWT tokens.
  • Supports all the standard JWT signing methods, including HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, and ES512.

Testing Packages

testify

It is a popular testing framework for Go. It provides a set of assertion functions and a mock library that can help simplify testing in Go.

Example

package main

import (
 "testing"

 "github.com/stretchr/testify/assert"
)

func TestAddition(t *testing.T) {
 result := 2 + 2
 assert.Equal(t, result, 4, "2 + 2 should equal 4")
}

func TestMultiplication(t *testing.T) {
 result := 3 * 3
 assert.NotEqual(t, result, 9, "3 * 3 should not equal 9")
}

Benefits

  • Its assertion functions are more expressive and provide better error messages than Go’s built-in testing package.
  • It provides a mocking library that can simplify the creation of test doubles.

mock

It is developed by Google and provides a powerful and easy-to-use framework for creating mock objects in Go.

Mock objects are used in unit testing to simulate the behavior of real objects that are used within an application.

With the mock package, you can easily create mock objects that can be used to test your code in isolation.

Example

type MyInterface interface {
    DoSomething() string
}

type MockMyInterface struct {
    mock.Mock
}

func (m *MockMyInterface) DoSomething() string {
    args := m.Called()
    return args.String(0)
}

func TestMyFunction(t *testing.T) {
    mockObj := new(MockMyInterface)
    mockObj.On("DoSomething").Return("mocked result")
    // pass the mock object to the function being tested
    result := MyFunction(mockObj)
    // assert the result is what we expect
    assert.Equal(t, "expected result", result)
}

Benefits

  • It provides a simple and easy-to-use interface for creating mock objects. You don’t need to be an expert in Go to create mock objects with this package.
  • It allows you to create mock objects for any interface, making it easy to test your code in isolation.
  • Creating mock objects manually can be a time-consuming and error-prone process. The mock package automates this process, allowing you to create mock objects quickly and efficiently.

Logging Package

logrus

It provides powerful logging functionality for Go, allowing developers to easily add logging capabilities to their applications.

Example

Here is an example of how to use logrus to log a message with the Info level:

package main

import (
    "github.com/sirupsen/logrus"
)

func main() {
    // Create a new logger instance
    logger := logrus.New()
    // Set the logging level to Info
    logger.SetLevel(logrus.InfoLevel)
    // Log a message with the Info level
    logger.Info("Hello, World!")
}

Benefits

  • With logrus, developers can define their own log levels and assign them a severity level. This allows for more fine-grained control over what log messages are outputted.
  • It provides an easy way to customize the format of log messages, including adding fields, changing the timestamp format, and more.
  • It can send log messages to a variety of output streams, such as the console, files, or remote services. This makes it easy to integrate with other systems, such as logging aggregators or monitoring tools.

Validation

validator

It is a great package for validating structs in Go. It provides a simple way to define validation rules for struct fields and run them against incoming data.

Example

package main

import (
 "fmt"
 "github.com/go-playground/validator/v10"
)

type Person struct {
 Name  string `validate:"required"`
 Email string `validate:"required,email"`
 Age   int    `validate:"gte=0,lte=130"`
}

func main() {
 person := Person{Name: "John", Email: "john@example.com", Age: 35}
 validate := validator.New()
 err := validate.Struct(person)
 
if err != nil {
  fmt.Println(err)
  return
}

 fmt.Println("Person is valid")
}

Benefits

  • It allows you to define validation rules using struct tags, which can be more concise and easier to read than writing custom validation functions.
  • It also supports a wide range of built-in validation rules and allows you to define custom validation rules if needed.

Routing Package

net/http

It is a package in the Go standard library that provides HTTP client and server implementations. It allows developers to build HTTP servers and clients, and interact with web APIs.

Example

package main

import (
 "fmt"
 "net/http"
)

func main() {

 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello, World!")
 })

 http.ListenAndServe(":8080", nil)
}

Benefits

  • As it’s part of the Go standard library, it’s always available without the need for external dependencies.
  • It’s easy to use and has a simple API, making it easy to build HTTP servers and clients.
  • It’s performant and can handle a high volume of requests.
  • It has built-in support for TLS/SSL, which is essential for secure communication over the web.
  • It includes useful features like connection pooling and timeouts to help manage resources and improve performance.
  • It has excellent support for testing HTTP servers and clients, making it easy to write automated tests for web applications.

Utility Packages

html/template

It provides functionality for generating HTML output. It is also a part of the standard library and allows developers to create templates that can be executed to generate HTML content.

Example

package main

import (
    "html/template"
    "os"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    tmpl, err := template.New("test").Parse("<p>My name is {{.Name}} and I am {{.Age}} years old.</p>")
    if err != nil {
        panic(err)
    }

    person := Person{Name: "John Smith", Age: 30}
    err = tmpl.Execute(os.Stdout, person)
    if err != nil {
        panic(err)
    }
}

// Output
<p>My name is John Smith and I am 30 years old.</p>

Benefits

  • It provides automatic escaping of user input, which helps to prevent cross-site scripting (XSS) attacks. This is done by escaping any HTML special characters that may be included in the input.

Image

It is also a part of the standard library and provides a set of functions and types for image manipulation. It includes support for various image formats and provides basic image processing capabilities.

Example

For instance, let’s see How to create a new PNG image and save it to the file.

package main

import (
 "image"
 "image/color"
 "image/png"
 "log"
 "os"
)

func main() {
 // Create a new 100x100 image
 img := image.NewRGBA(image.Rect(0, 0, 100, 100))

 // Fill the image with blue color
 for x := 0; x < 100; x++ {
  for y := 0; y < 100; y++ {
   img.Set(x, y, color.RGBA{0, 0, 255, 255})
  }
 }

 // Save the image to a file
 f, err := os.Create("blue.png")
 if err != nil {
  log.Fatal(err)
 }
 defer f.Close()

 if err := png.Encode(f, img); err != nil {
  log.Fatal(err)
 }
}

Benefits

  • As it’s part of the standard library, there’s no need to install any additional packages.
  • It provides support for various image formats, including PNG, JPEG, GIF, BMP, etc.
  • It provides basic image processing capabilities, such as resizing, cropping, and rotating.

samber/lo

It’s a Go implementation of the popular JavaScript utility library called Lodash.

Lodash is a collection of utility functions that simplify working with arrays, numbers, objects, strings, and other data types in JavaScript.

samber/lo provides similar utility functions in Go that help in simplifying code and making it more readable.

Example

For instance, you can use the Contains function to check the existence of a given element within the slice:

package main

import (
 "fmt"
 "github.com/samber/lo"
)

func main() {
 slice := []int{1, 2, 3, 4, 5}
 if lo.Contains(slice, 3) {
  fmt.Println("Slice contains 3")
 } else {
  fmt.Println("Slice does not contain 3")
 }
}

Benefits

  • It supports generics.
  • By using samber/lo, developers can take advantage of the power of Lodash in their Go projects and streamline their development process.

duke-git/lancet

It is a comprehensive, efficient, and reusable util function library for Golang. Inspired by the java apache common package and lodash.js.

The major difference between lancet and samber/lo is it provides utilities of different categories like,

  • slice
  • time
  • encryption
  • files
  • formatters
  • operators(You’ve definitely struggled with ternary😞), and many more.

Example

Let’s believe Ternary works in Golang, too!

package mainimport (
  "fmt"
  "github.com/duke-git/lancet/v2/condition"
)

func main() {

   conditionTrue := 2 > 1
   result1 := condition.TernaryOperator(conditionTrue, 0, 1)
   fmt.Println(result1)

   conditionFalse := 2 > 3
   result2 := condition.TernaryOperator(conditionFalse, 0, 1)
   fmt.Println(result2)
}

// Output:
// 0
// 1

Benefits

  • It can help reduce the amount of boilerplate code needed for common operations, as it supports the utilities of a wider range.

Caching

go-redis

It is a powerful and flexible Redis client for Go that can help you build high-performance applications that interact with Redis data stores.

Example

import (
    "github.com/go-redis/redis/v8"
    "fmt"
)

func main() {
    // create a Redis client
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    // set a key-value pair in Redis
    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }

    // get the value for a given key from Redis
    val, err := rdb.Get(ctx, "key").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key", val)
}

Benefits

  • It offers features such as connection pooling, pipelining, and automatic reconnection to ensure that your Redis queries are executed quickly and efficiently.
  • It supports a wide range of Redis data types and operations, including strings, hashes, lists, sets, sorted sets, and more. It also provides support for Redis transactions, and pub/sub messaging.

AWS integration

aws-sdk-go

It is a set of packages designed to interact with AWS services. The package includes a large number of clients that can be used to interact with various AWS services such as S3, DynamoDB, EC2, and many others.

It provides a wide range of functionalities like signing requests, managing credentials, and making API requests.

Example

Here is an example of using aws-sdk-go to interact with Amazon S3:

package main

import (
 "fmt"
 "github.com/aws/aws-sdk-go/aws"
 "github.com/aws/aws-sdk-go/aws/session"
 "github.com/aws/aws-sdk-go/service/s3"
)

func main() {
 // Create a new session to use for the S3 client
 sess, err := session.NewSession(&aws.Config{
  Region: aws.String("us-west-2"),
 })
 if err != nil {
  panic(err)
 }

 // Create an S3 client
 svc := s3.New(sess)

 // Get the list of S3 buckets
 result, err := svc.ListBuckets(nil)
 if err != nil {
  panic(err)
 }

 // Print the bucket names
 fmt.Println("S3 Buckets:")
 for _, b := range result.Buckets {
  fmt.Printf("* %s created on %s\n", aws.StringValue(b.Name), aws.TimeValue(b.CreationDate))
 }
}

Benefits

  • It’s better than similar libraries because it’s built and maintained by AWS and is always up-to-date with the latest API changes.
  • It provides a consistent interface across all AWS services, making it easy to work with multiple services in the same application.

Documentation

go-swagger

It is a popular package for building RESTful APIs by defining API operations in Swagger 2.0 or OpenAPI 3.0 specifications. It generates documentation, validation code, and client and server boilerplate code according to a given input.

It generates the documentation from given swagger.yml file.

Example

swagger generate server -A <api-name> -f ./swagger.yml

Benefits

  • It simplifies the process of building RESTful APIs by allowing developers to define their APIs using a widely-used and well-documented specification format (Swagger/OpenAPI).
  • It includes support for a variety of features, such as API key authentication, OAuth2, and response code validation, that can make building secure and reliable APIs easier and more efficient.

Terminating thoughts

Golang offers a wide range of powerful packages that are effective in the aspects of performance, simplicity, and reliability.

By leveraging those packages, developers can streamline their development process and create robust and scalable applications with ease.

Please drop a comment if you think any other packages should be involved here, I would like to add up the same if it can be helpful to the developers.


Similar trending articles


nidhi-d image
Nidhi Davra
Web developer@canopas | Gravitated towards Web | Eager to assist


nidhi-d image
Nidhi Davra
Web developer@canopas | Gravitated towards Web | Eager to assist

background-image

Get started today

Let's build the next
big thing!

Let's improve your business's digital strategy and implement robust mobile apps to achieve your business objectives. Schedule Your Free Consultation Now.

Get Free Consultation
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.