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!
We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!
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
Visit Golang: gorm with MySQL and gin for full implementation reference.
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
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
sqlx
over the standard database/sql
package is the ability to work with result sets more easily.Note
database/sql
, then jmoiron/sqlx
OR go-sql-driver
can make your life easy while using it!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
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
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
mock
package automates this process, allowing you to create mock objects quickly and efficiently.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
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 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: "[email protected]", Age: 35}
validate := validator.New()
err := validate.Struct(person)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Person is valid")
}
Benefits
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
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 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
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 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,
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 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 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 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
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.
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 ConsultationGet 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