Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Building Distributed Applications in Gin
Building Distributed Applications in Gin

Building Distributed Applications in Gin: A hands-on guide for Go developers to build and deploy distributed web apps with the Gin framework

Arrow left icon
Profile Icon Mohamed Labouardy
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (14 Ratings)
Paperback Jul 2021 482 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Mohamed Labouardy
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (14 Ratings)
Paperback Jul 2021 482 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $35.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Building Distributed Applications in Gin

Chapter 1: Getting Started with Gin

This chapter will give you a foundational understanding of what the Gin framework is, how it works, and its features. We'll also supply guidelines for setting up the Go runtime and development environment. Moreover, we'll discuss the advantages of using Gin as a web framework for building distributed applications. We will finish this chapter by learning to write our first Gin-based web application.

In this chapter, we will cover the following topics:

  • What is Gin?
  • Go runtime and integrated development environment (IDE)
  • Go modules and dependency management
  • Writing a Gin web application

By the end of this chapter, you will be able to build a basic HTTP server with the Gin web framework.

Technical requirements

To follow along with this chapter, you will need the following:

  • Some programming experience. The code in this chapter is pretty simple, but it helps to know something about Go.
  • A tool to edit your code with. Any text editor you have will work fine. Most text editors have good support for Go. The most popular are Visual Studio Code (VSCode) (free), GoLand (paid), and Vim (free).
  • A command terminal. Go works well using any Terminal on Linux and Mac, and on PowerShell or CMD in Windows.

The code bundle for this chapter is hosted on GitHub at https://github.com/PacktPublishing/Building-Distributed-Applications-in-Gin/tree/main/chapter01.

What is Gin?

Before deep diving into the Gin web framework, we need to understand why Go is a top choice when it comes to building scalable and distributed applications.

Go (also referred to as Golang) is an open source programming language, developed by Robert Griesemer, Rob Pike, and Ken Thompson within Google in 2007. It is a compiled, statically typed language designed to enable users to easily write reliable, scalable, and highly efficient applications. The key features of Go are as follows:

  • Simple and consistent: Go has a rich set of library packages with powerful standard libraries for testing, error management, and concurrency.
  • Fast and scalable: Go is a general-purpose programming language developed for the multi-core reality of today's computers. It has built-in concurrency with Goroutines and channels. Goroutines provide lightweight, threaded execution. Declaring a Goroutine is as simple as adding the go keyword before a function.
  • Efficient: Go provides efficient execution and compilation. Go is also statically linked, which means that the compiler invokes a linker in the last step that resolves all library references. This means we would get one binary executable after compiling a Go program with no external dependencies. Moreover, it offers efficient memory utilization with a built-in garbage collector (Go exhibits many similarities with low-level programming languages such as C or C++).
  • Community and support: Go is backed by Google and has an ever growing ecosystem and numerous contributors to the language on GitHub. Moreover, many online resources (tutorials, videos, and books) are available for getting started with Go.

Go has become hugely popular among enterprises and the open source community. Based on the StackOverflow Developer Survey 2020 (https://insights.stackoverflow.com/survey/2020), Go is in the top 5 of the most loved programming languages:

Figure 1.1 – Most loved programming languages according to the StackOverflow Survey 2020

Figure 1.1 – Most loved programming languages according to the StackOverflow Survey 2020

Golang is known to be the number one choice when it comes to building large-scale, complex tools and cloud-based applications. The following image highlights the main open source projects that have been developed using Go:

  • Docker: A solution that's used to create, deploy, and run applications using containers.
  • Kubernetes: A container orchestration platform for managing containers across a fleet of nodes/machines.
  • Etcd: A reliable distributed key-value store used to store data for a distributed system or application.
  • InfluxDB: A scalable time-series database designed to handle high write and query loads.
  • CoreOS: A lightweight operating system designed to deploy container-based applications.
  • Terraform: An infrastructure-as-code tool for building, changing, and versioning cloud infrastructure.
  • CockroachDB: A cloud-native SQL database for data-intensive applications.
  • Consul: A distributed store with service discovery, service mesh, and health check monitoring capabilities:
Figure 1.2 – Open source tools powered by Go

Figure 1.2 – Open source tools powered by Go

As we can see, Go is a solid language for distributed systems and infrastructure tools. Docker, Kubernetes, Prometheus, and others are built using Go.

Go is also known for building web applications of all shapes and sizes. This is partly due to the fantastic work that has been put into making the standard library clean, consistent, and easy to use. Perhaps one of the most important packages for any budding Go web developer is the net/http package. This package allows you to build HTTP servers in Go with its powerful compositional constructs.

To build a web application, you'll need to build an HTTP server. The client (for example, a browser) makes an HTTP request with some information; the server then processes that request and returns a response. The response can be in JSON, XML, or HTML format:

Figure 1.3 – HTTP client-server communication

Figure 1.3 – HTTP client-server communication

This pattern of request-response is one of the key focal points in building web applications in Go.

While the net/http package allows you to craft a web application easily, the routing mechanism is not so powerful, especially for complex applications. That's where a web framework comes into play. The top Golang web frameworks are listed in the following table:

Gin is possibly the most used and largest running Go web framework. The framework has already harvested 48,210 stars and 5,100 forks in GitHub, which shows that the framework is very popular. This modular framework can be extended easily with minimal fuss. It is great to use because many components can be reused with a direct net/http package.

Important note

Another strong but conservative framework is Gorilla/Mux. It has one of the biggest online communities with many resources on the internet to teach you how to build end-to-end web applications.

According to the official documentation https://gin-gonic.com/docs/, Gin is described as follows:

"Gin is an HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin".

Gin is a minimalistic web framework suitable for building web applications, microservices, and RESTful APIs. It reduces boilerplate code by creating reusable and extensible pieces of code: you can write a piece of middleware that can be plugged into one or more request handlers. Moreover, it comes with the following key features:

  • Well documented: The documentation for Gin is broad and comprehensive. Most tasks that you will need to do relating to the router can be found easily in the docs.
  • Simplicity: Gin is a pretty minimalistic framework. Only the most essential features and libraries are included, with little to no boilerplate to bootstrap applications, making Gin a great framework for developing highly available REST APIs.
  • Extensible: The Gin community has created numerous pieces of well-tested middleware that make developing for Gin a charm. Features include compression with GZip, authentication with an authorization middleware, and logging with external solutions such as Sentry.
  • Performance: Gin runs 40x faster than Martini and runs comparatively well compared to other Golang frameworks. The following is the results of a benchmark I ran against multiple Go libraries:
Figure 1.4 – Golang web framework benchmarks

Figure 1.4 – Golang web framework benchmarks

Important note

This benchmark was performed on a macOS High Sierra, 2.7 GHz Intel Core i7, 16 GB DDR3 computer, with Go 1.15.6 as the runtime environment.

That being said, before you can write your first line of Go code, you'll need to set up the environment. Let's start by installing Go.

Setting up the Go environment

At the time of writing this book, the latest version of Go is Go 1.15.6. To install Go, you can either download or use the official binary distributions, or you can install Go from the source code (https://github.com/golang/go).

Important note

The official binary distributions are available for FreeBSD (release 8 and above), Linux (2.6.23 and above), macOS (Snow Leopard and above), and Windows (XP and above). Both the 32-bit (386) and 64-bit (amd64) x86 processor architectures are supported. For FreeBSD and Linux, the ARM processor architecture is also supported.

To install Go, download the distribution package from the https://golang.org/dl/ web page, as shown here, and choose the file that's appropriate for your platform:

Figure 1.5 – Golang available packages

Figure 1.5 – Golang available packages

Once you have the distribution package, install Go according to your platform of choice. We will cover this in the following sections.

Linux/FreeBSD

To install Go on Linux or FreeBSD, you must download go.-.tar.gz. The latest Go for Linux on a 64-bit architecture is go1.15.6.linux-amd64.tar.gz:

wget -c https://golang.org/dl/go1.15.6.linux-amd64.tar.gz   //64bit
wget -c https://golang.org/dl/go1.15.6.linux-386.tar.gz     //32bit

Download the archive and extract it into the /usr/local folder. Then, run the following command as root or through sudo:

tar -C /usr/local -xzf go1.15.6.linux-amd64.tar.gz

Add /usr/local/go/bin to the PATH environment variable. You can do this by adding the following line to $HOME/.profile or /etc/profile (for a system-wide installation):

export PATH=$PATH:/usr/local/go/bin

Verify that you've installed Go by opening a command prompt and typing the following command:

go version

This command should display the installed version of Go:

Figure 1.6 – Installed version of Go

Figure 1.6 – Installed version of Go

Let's move on to see how to set up a Go environment on Windows.

Windows

To install Go on Windows, you can either use the MSI installer or the ZIP archive. Installing from MSI is easier. The latest Go for Windows on a 64-bit architecture is go1.15.6.windows-amd64.msi. You will then need to execute one of the following commands based on your system:

wget -c https://golang.org/dl/go1.15.6.windows-amd64.msi   //64bit
wget -c https://golang.org/dl/go1.15.6.windows-386.msi     //32bit

Open the MSI file you downloaded and follow the prompts to install Go. By default, the installer will place Go at C:\Go and set up C:\Go\bin in your PATH environment variable. You can change the location as needed:

Figure 1.7 – Golang installation wizard

Figure 1.7 – Golang installation wizard

After installing Go, you will need to close and reopen any open command prompts so that changes to the environment that have been made by the installer are reflected in the command prompt.

Important note

Using the ZIP archive is easy as well. Extract the files into a directory (for example, C:\Go) and add the bin subdirectory to your PATH variable.

Once installed, click on the Start menu. Then, in the menu's search box, type cmd. After, press the Enter key. In the command prompt window that appears, type the go version command, as shown here:

Figure 1.8 – Installed version of Go

Figure 1.8 – Installed version of Go

You'll see go version go1.15.6 windows/amd64, as shown in the preceding screenshot. With that, you're all set up!

MacOS

For MacOS, you can download the appropriate PKG file; that is, go1.15.6.darwin-amd64.pkg (at the time of writing this book). Once downloaded, run through the installation wizard. The package will install the distribution to /usr/local/go and place the /usr/local/go/bin directory in your PATH environment variable:

Figure 1.9 – Installing Go on MacOS

Figure 1.9 – Installing Go on MacOS

You'll need to restart your terminal, or run this command in your Terminal:

source ~/.profile

Alternatively, you can use Homebrew to install Go. This can be as simple as doing the following:

brew install [email protected]

The Terminal window will give you feedback regarding the installation process of Go. It may take a few minutes before the installation is complete. Verify that you've installed Go by opening a command prompt and typing the go version command.

Important note

In the future, to update Go, you can run the following commands to update Homebrew and then update Go. You don't have to do this now as you've just installed the latest version:

brew update
brew upgrade golang

Now that you've installed Go, you need to set it up properly. Go development tools are designed to work with code maintained in public repositories, and the model is the same, regardless of whether you're developing an open source program or something else. Go code is developed in a workspace. A workspace is made up of three directories, namely the following:

  • bin: This will contain all you Go executable binaries.
  • src: This will store your source files, which are organized in packages, with one subdirectory in the src directory representing one package.
  • pkg: This will store your package objects.

The default directory for the Go workspace is the home directory with a go subdirectory or $HOME/go. Issue the following command to create the directory structure for your Go workspace:

mkdir -p $HOME/go/{bin,src,pkg}

The -p option tells mkdir to create all the parents in the directory, even if they don't currently exist. Using {bin, src, pkg} creates a set of arguments for mkdir and tells it to create the bin, src, and pkg directories. This will ensure the following directory structure is now in place:

The go, bin and  src folders should be at the same level (remove extra spaces from go and src folders, so the folders are aligned with bin folder)
$HOME 
 └── go 
 ├── bin 
 └── src 

Next, you need to set the GOPATH environment variable, as follows:

export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

You can verify your $PATH has been updated by using the echo command and inspecting the output:

echo $PATH

You should see your $GOPATH/bin in your home directory. If you were logged in as USER, you will see /Users/USER/go/bin in the path:

/Users/USER/go/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

With the Go workspace and GOPATH created, we can go ahead and set up the development environment.

Integrated development environment

Throughout this book, I will be using an IDE to write RESTful API and services. Using an IDE can boost your productivity since it provides rich features such as autocompletion, highlighting code, a powerful built-in debugger, and custom extensions. There are many IDEs available. In this book, I will be using VSCode.

To install VSCode, download the appropriate package based on your system from https://code.visualstudio.com/download:

Figure 1.10 – VS Code – available packages

Figure 1.10 – VS Code – available packages

Note

Mac users can also use Brew to install VSCode with the following command:

brew install --cask visual-studio-code

Once downloaded, run the setup wizard and follow the instructions. Once the installation is complete, launch VSCode. You will be presented with the following start screen:

Figure 1.11 – VSCode user interface

Figure 1.11 – VSCode user interface

VSCode supports all the popular programming languages and Git integration by default. You can also install extensions to extend the functionality of VSCode. The VS Code marketplace contains a huge list of free community plugins and extensions. To enable support for Golang, you need to install an extension called Go by navigating to the Extensions tab from the left sidebar:

Figure 1.12 – Golang extension for VSCode

Figure 1.12 – Golang extension for VSCode

Click on the Install button and then restart VSCode for the changes to take effect.

Installing Go tools

Next, we will install the following Go tools, which are a set of packages that help improve your development workflow and overall experience while writing code:

Important Note

A complete list of the available Go tools can be found at https://pkg.go.dev/golang.org/x/tools.

To install the tools, click on View | Command Pallete, or use the Ctrl + Shift + P shortcut and type goinstall update/tools:

Figure 1.13 – Available Go tools on VSCode

Figure 1.13 – Available Go tools on VSCode

Check all the dependencies and click on OK. It will take some time to download all the dependencies:

Figure 1.14 – Go tools installation

Figure 1.14 – Go tools installation

With Go installed and configured on your computer, you are now ready to install the Gin framework.

Installing and configuring Gin

Gin is a third-party package. To install Gin in Go projects, we need to use the go get command. The command takes the URL of the package to be installed as an argument. Issue the following command to install the gin package from GitHub:

go get github.com/gin-gonic/gin

Note

If you're running Go 1.16 and above, you need to disable Go modules via the GO111MODULE=off option.

When checking out the gin package, the go get command creates a Gin directory in the $GOPATH/src path. The directory will contain the source code of the Gin framework:

Figure 1.15 – Gin package source code

Figure 1.15 – Gin package source code

Begin by creating the hello-world project directory under $GOHOME/src/hello-world or any directory that seems appropriate:

mkdir -p $GOHOME/src/hello-world 
cd $GOHOME/src/hello-world

Open the folder with VSCode and create a main.go file inside the project folder that contains the following content:

package main
import "github.com/gin-gonic/gin"
func main() {
   router := gin.Default()
   router.GET("/", func(c *gin.Context) {
       c.JSON(200, gin.H{
           "message": "hello world",
       })
   })
   router.Run()
}

The first line, package main, indicates that this is the main module in this project. The import section is for importing the gin package. This package provides us with the router variable, which is declared right below import and the API context to be used while we send the response in our main function.

Next, we create an HTTP GET method on the root (/) resource and define a function to be called when HTTP requests hit the root endpoint. The function sends a JSON response with a status code of 200 (OK) with a body of "message": "test successful".

Finally, we must deploy the router on port 8080 using the router.Run() method. The following diagram summarizes how an HTTP request is processed in Gin:

Figure 1.16 – Parsing incoming HTTP requests with Gin

Figure 1.16 – Parsing incoming HTTP requests with Gin

To run the app, execute the following command from the terminal session:

go run main.go

All the files and commands executed henceforth will be within this directory. If you followed the setup process, you should see the following output in your Terminal:

Figure 1.17 – Gin server logs

Figure 1.17 – Gin server logs

Point your favorite browser to http://localhost:8080. You should see a "hello world" message:

Figure 1.18 – Hello world example

Figure 1.18 – Hello world example

Awesome – you have successfully started an HTTP server in Go with the Gin framework.

Back to the terminal, Gin will trace the HTTP requests:

Figure 1.19 – Tracing incoming HTTP requests

Figure 1.19 – Tracing incoming HTTP requests

You can use a cURL command to issue an HTTP request:

curl -X GET http://localhost:8080

Alternatively, you can use an advanced REST client such as Postman. You can download the right version based on your platform from the following URL: https://www.getpostman.com/apps.

Once it has downloaded, run the wizard and open Postman. Set the fields as follows:

  • HTTP method: GET
  • URL: http://localhost:8080
  • Headers: Set Content-Type to application/json

The request should be configured like so:

Figure 1.20 – GET request with the Postman client

Figure 1.20 – GET request with the Postman client

It's worth mentioning that by default, the HTTP server is listening on port 8080. However, if the port is being used by another application, you can define a different port by adding an argument to the Run method:

r.Run(":5000")

This command will run the server on port 5000, as shown in the following screenshot:

Figure 1.21 – Running the Gin server on port 5000

Figure 1.21 – Running the Gin server on port 5000

Note that the port parameter needs to be passed as a string, prepended by colon punctuation.

You should now be familiar with the basics of building and running a simple web application. In the next few sections, we will cover how to enhance those functionalities with third-party packages. But before we do that, let's cover how to manage Go dependencies.

Dependency management in Golang

For now, the code is stored locally. However, it's recommended to store the source code in a remote repository for versioning. That's where a solution such as GitHub comes into play. Sign up for a free account at https://github.com. Then, create a new GitHub repository called hello-world:

Figure 1.22 – New GitHub repository

Figure 1.22 – New GitHub repository

Next, initialize the repository with the following commands:

git init 
git remote add origin https://github.com/mlabouardy/hello-world.git

Commit the main.go file to the remote repository by executing the following commands:

git add . 
git commit -m "initial commit" 
git push origin master

Your repository should now look like this:

Figure 1.23 – Versioning main.go in Git

Figure 1.23 – Versioning main.go in Git

We can stop here. However, if you're working within a team, you will need some way to ensure all team members are using the same Go version and packages. That's where Go modules come into the picture. Go modules were introduced in 2018 to make dependency management a lot easier.

Note

Starting with Go 1.16, Go modules are the default way to manage external dependencies.

In the project folder, run the following command to create a new module:

go mod init hello-world

This command will create a go.mod file that contains the following content. The file defines projects requirements and locks dependencies to their correct versions (similar to package.json and package-lock.json in Node.js):

module github.com/mlabouardy/hello-world
go 1.15

To add the Gin package, we can issue the go get command. Now, our go.mod file will look like this:

module github.com/mlabouardy/hello-world
go 1.15
require github.com/gin-gonic/gin v1.6.3

A new file called go.sum will be generated upon adding the Gin framework (the output was cropped for brevity). You may assume it's a lock file. But in fact, go.mod already provides enough information for 100% reproducible builds. The other file is just for validation purposes: it contains the expected cryptographic checksums of the content of specific module versions. You can think of it as an additional security layer to ensure that the modules your project depends on do not change unexpectedly, whether for malicious or accidental reasons:

github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
github.com/go-playground/locales v0.13.0/go.mod

You can list your dependencies with the following command:

go list -m all

The output is as follows:

github.com/mlabouardy/hello-world
github.com/davecgh/go-spew v1.1.1
github.com/gin-contrib/sse v0.1.0
github.com/gin-gonic/gin v1.6.3
github.com/go-playground/assert/v2 v2.0.1
github.com/go-playground/locales v0.13.0
github.com/go-playground/universal-translator v0.17.0
github.com/go-playground/validator/v10 v10.2.0
github.com/golang/protobuf v1.3.3
github.com/google/gofuzz v1.0.0
github.com/json-iterator/go v1.1.9
github.com/leodido/go-urn v1.2.0
github.com/mattn/go-isatty v0.0.12
github.com/modern-go/concurrent v0.0.0-20180228061459
e0a39a4cb421
github.com/modern-go/reflect2 v0.0.0-20180701023420
4b7aa43c6742
github.com/pmezard/go-difflib v1.0.0
github.com/stretchr/objx v0.1.0
github.com/stretchr/testify v1.4.0
github.com/ugorji/go v1.1.7
github.com/ugorji/go/codec v1.1.7
golang.org/x/sys v0.0.0-20200116001909-b77594299b42
golang.org/x/text v0.3.2
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405
gopkg.in/yaml.v2 v2.2.8

Important Note

To remove unused dependencies, you can use the go mod tidy command.

Finally, add the go.mod and go.sum files to the remote repository using the following commands:

git add .
git commit -m "dependency management"
git push origin master

The updated repository will look as follows:

Figure 1.24 – Managing dependencies with Go modules

Figure 1.24 – Managing dependencies with Go modules

It's worth mentioning that the downloaded modules are stored locally in your $GOPATH/pkg/mod directory. However, sometimes, it's useful to store the modules or third-party packages that your project depends on and place them in a folder, so that they can be checked into version control. Fortunately, Go modules support vendoring:

go mod vendor

This command will create a vendor directory in your project folder that contains all your third-party dependencies. You can now commit this folder to your remote Git repository to ensure the stability of your future builds, without having to rely on external services:

Figure 1.25 – Vendoring dependencies

Figure 1.25 – Vendoring dependencies

Sometimes, you may wonder why a specific package is a dependency. You can answer this by analyzing or visualizing the project dependencies. To do so, we can use the go mod graph command to display the list of modules in the go.mod file:

go mod graph | sed -Ee 's/@[^[:blank:]]+//g' | sort | uniq >unver.txt

This command will generate a new file called unver.txt containing the following content (the output has been cropped for brevity):

github.com/gin-contrib/sse github.com/stretchr/testify
github.com/gin-gonic/gin github.com/gin-contrib/sse
github.com/gin-gonic/gin github.com/go-playground/validator/v10
github.com/gin-gonic/gin github.com/golang/protobuf
github.com/gin-gonic/gin github.com/json-iterator/go
github.com/gin-gonic/gin github.com/mattn/go-isatty
github.com/gin-gonic/gin github.com/stretchr/testify
github.com/gin-gonic/gin github.com/ugorji/go/codec
github.com/gin-gonic/gin gopkg.in/yaml.v2

Then, create a graph.dot file containing the following content:

digraph {
    graph [overlap=false, size=14];
    root="$(go list -m)";
    node [ shape = plaintext, fontname = "Helvetica", 
          fontsize=24];
    "$(go list -m)" [style = filled, 
                     fillcolor = "#E94762"];

This content will generate a graph structure using the DOT language. We can use DOT to describe graphs (directed or not). That being said, we will inject the output of unvert.txt into the graph.dot file with the following commands:

cat unver.txt | awk '{print "\""$1"\" -> \""$2"\""};' >>graph.dot
echo "}" >>graph.dot
sed -i '' 's+\("github.com/[^/]*/\)\([^"]*"\)+\1\\n\2+g' graph.dot

This results in a module dependency graph:

Figure 1.26 – Module dependency graph

Figure 1.26 – Module dependency graph

We can now render the results with Graphviz. This tool can be installed with the following commands, based on your operation system:

  • Linux: You can download the official package based on your package manager. For Ubuntu/Debian, use the following command:
    apt-get install graphviz
  • MacOS: You can use the Homebrew utility for MacOS:
    brew install graphviz
  • Windows: You can use the Chocolatey (https://chocolatey.org/install) package manager for Windows:
    choco install graphviz.portable

Once Graphviz has been installed, execute the following command to convert the graph.dot file into .svg format:

sfdp -Tsvg -o graph.svg graph.dot

A graph.svg file will be generated. Open the file with the following command:

open graph.svg

This results in the following directed graph:

Figure 1.27 – Visually analyzing module dependencies

Figure 1.27 – Visually analyzing module dependencies

This graph perfectly shows the dependencies among the modules/packages of the hello-world project.

Note

Another way of generating a dependencies graph is by using the modgv utility (https://github.com/lucasepe/modgv). This tool converts go mod graph output into GraphViz's DOT language with a single command.

Now that the source code has been versioned in GitHub, we can go further and explore how to write a custom function handler for Gin routes.

Writing a custom HTTP handler

You can create a handler function that takes *gin.Context as an argument and serves a JSON response with a status code of 200. Then, you can register the handler using the router.Get() function:

package main
import "github.com/gin-gonic/gin"
func IndexHandler(c *gin.Context){
   c.JSON(200, gin.H{
       "message": "hello world",
   })
}
func main() {
   router := gin.Default()
   router.GET("/", IndexHandler)
   router.Run()
}

Important note

Separating the handler function from the router will be useful in the advanced chapters of this book, when unit testing is tackled.

The biggest strength of the Gin framework is its ability to extract segments from the request URL. Consider the following example:

/users/john
/hello/mark

This URL has a dynamic segment:

  • Username: Mark, John, Jessica, and so on

You can implement dynamic segments with the following :variable pattern:

func main() {
   router := gin.Default()
   router.GET("/:name", IndexHandler)
   router.Run()
}

The last thing we must do is get the data from the variable. The gin package comes with the c.Params.ByName() function, which takes the name of the parameter and returns the value:

func IndexHandler(c *gin.Context) {
   name := c.Params.ByName("name")
   c.JSON(200, gin.H{
       "message": "hello " + name,
   })
}

Rerun the app with the go run command. Hit the http://localhost:8080/mohamed link on your browser; the user will be returned:

Figure 1.28 – Example of the path parameter

Figure 1.28 – Example of the path parameter

Now, we know that every time we hit the GET /user route, we get a response of "hello user." If we hit any other route, it should respond with a 404 error message:

Figure 1.29 – Error handling in Gin

Figure 1.29 – Error handling in Gin

Gin can also handle HTTP requests and responses in XML format. To do so, define a user struct with firstName and lastName as attributes. Then, use the c.XML() method to render XML:

func main() {
   router := gin.Default()
   router.GET("/", IndexHandler)
   router.Run()
}
type Person struct {
     XMLName xml.Name `xml:"person"`
     FirstName     string   `xml:"firstName,attr"`
     LastName     string   `xml:"lastName,attr"`
}
func IndexHandler(c *gin.Context) {
     c.XML(200, Person{FirstName: "Mohamed", 
                       LastName: "Labouardy"})
}

Now, rerun the application. If you navigate to http://localhost:8080, the server will return an XML response, as follows:

Figure 1.30 – XML response

Figure 1.30 – XML response

Congratulations! At this point, you have a Go programming workspace set up on your local machine, as well as Gin configured. Now, you can begin a coding project!

Summary

In this chapter, we gave you an introduction to the Go programming language. We learned how to set up the runtime and development environments. We also understood the GOPATH environment variable, which is a workspace definition in Go, and we now know that all packages and projects reside on that path.

Later, we explored the different Go web frameworks and learned why Gin is the most popular for building distributed web applications. Finally, we learned how to write our first hello world project with Gin from scratch.

In the next chapter, we will get our hands dirty and start building a distributed RESTful API with the Gin framework.

Questions

  1. Why is Golang popular?
  2. Which are the best Golang frameworks for web development?
  3. What's a Go module?
  4. What's the default port of an HTTP server written in the Gin framework?
  5. What methods are used to render JSON and XML responses?

Further reading

  • Hands-On Serverless Applications with Go, Mohamed Labouardy, by Packt Publishing
  • Hands-On RESTful Web Services with Go - Second Edition, Naren Yellavula, by Packt Publishing
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore the commonly used functionalities of Gin to build web applications
  • Become well-versed with rendering HTML templates with the Gin engine
  • Solve commonly occurring challenges such as scaling, caching, and deployment

Description

Gin is a high-performance HTTP web framework used to build web applications and microservices in Go. This book is designed to teach you the ins and outs of the Gin framework with the help of practical examples. You’ll start by exploring the basics of the Gin framework, before progressing to build a real-world RESTful API. Along the way, you’ll learn how to write custom middleware and understand the routing mechanism, as well as how to bind user data and validate incoming HTTP requests. The book also demonstrates how to store and retrieve data at scale with a NoSQL database such as MongoDB, and how to implement a caching layer with Redis. Next, you’ll understand how to secure and test your API endpoints with authentication protocols such as OAuth 2 and JWT. Later chapters will guide you through rendering HTML templates on the server-side and building a frontend application with the React web framework to consume API responses. Finally, you’ll deploy your application on Amazon Web Services (AWS) and learn how to automate the deployment process with a continuous integration and continuous delivery (CI/CD) pipeline. By the end of this Gin book, you will be able to design, build, and deploy a production-ready distributed application from scratch using the Gin framework.

Who is this book for?

This book is for Go developers who are comfortable with the Go language and seeking to learn REST API design and development with the Gin framework. Beginner-level knowledge of the Go programming language is required to make the most of this book.

What you will learn

  • Build a production-ready REST API with the Gin framework
  • Scale web applications with event-driven architecture
  • Use NoSQL databases for data persistence
  • Set up authentication middleware with JWT and Auth0
  • Deploy a Gin-based RESTful API on AWS with Docker and Kubernetes
  • Implement a CI/CD workflow for Gin web apps

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 23, 2021
Length: 482 pages
Edition : 1st
Language : English
ISBN-13 : 9781801074858
Vendor :
Google
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 23, 2021
Length: 482 pages
Edition : 1st
Language : English
ISBN-13 : 9781801074858
Vendor :
Google
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Hands-On RESTful Web Services with Go
$43.99
Mastering Go – Third Edition
$54.99
Building Distributed Applications in Gin
$48.99
Total $ 147.97 Stars icon
Banner background image

Table of Contents

15 Chapters
Section 1: Inside the Gin Framework Chevron down icon Chevron up icon
Chapter 1: Getting Started with Gin Chevron down icon Chevron up icon
Section 2: Distributed Microservices Chevron down icon Chevron up icon
Chapter 2: Setting Up API Endpoints Chevron down icon Chevron up icon
Chapter 3: Managing Data Persistence with MongoDB Chevron down icon Chevron up icon
Chapter 4: Building API Authentication Chevron down icon Chevron up icon
Chapter 5: Serving Static HTML in Gin Chevron down icon Chevron up icon
Chapter 6: Scaling a Gin Application Chevron down icon Chevron up icon
Section 3: Beyond the Basics Chevron down icon Chevron up icon
Chapter 7: Testing Gin HTTP Routes Chevron down icon Chevron up icon
Chapter 8: Deploying the Application on AWS Chevron down icon Chevron up icon
Chapter 9: Implementing a CI/CD Pipeline Chevron down icon Chevron up icon
Chapter 10: Capturing Gin Application Metrics Chevron down icon Chevron up icon
Assessments Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(14 Ratings)
5 star 57.1%
4 star 35.7%
3 star 0%
2 star 7.1%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Thomas Schnieders Sep 06, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I got the book as a preview to read. A big advantage of the book is the structure. It does not only focus on implementation details but also covers a large part of the topics around CI/CD. Furthermore, modern tools like Prometheus, Grafana or the ELK-Stack are used (at this point I would have preferred Loki in combination with Grafana as logging framework though).Topics around security are also covered. What I also find particularly good is the fact that in many places alternative tolls and frameworks to the solutions used are presented or mentioned.In some places the book is a bit "chatty". Especially when it comes to the use of git.On the whole, however, the book is very good, with clear examples that I could already use in my current work one or two times.However, you should have some experience with Go, because the book is not suitable for learning the language.
Amazon Verified review Amazon
Angel Psiakis Sep 12, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really enjoyed reading this book. Although I love Go and consider myself a senior software engineer, there are always moments where I'm thinking how would someone else do a certain thing.This book takes you through the journey of building an app using the popular framework Gin in an iterative fashion. Each iteration adds features to your app. You start by setting up your data model / business logic / routing, defining your api, adding persistence and caching. A little break for a bit of React and then the fun starts: scaling, deploying, monitoring.I found it to be well written both in readability and technical terms.I would have preferred to go for OpenApi v2 instead v3 and spending a little more time on tracing when ELK is available, but I might be nitpicking.Recommended to everyone who wants a good "holistic" introduction to building/deploying/monitoring an microservices app in Go on AWS.
Amazon Verified review Amazon
S. Wiseman Jul 26, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been a software developer for 10+ years and have read many software framework books/manuals. I find they can sometimes offer very little extra information when compared to the framework documentation, but that is not the case with this book. It is rich with information and takes you through a complete small project journey using a great language and framework.I felt the book was very well balance, it deep dived when it needed to and gave an overview when it was dealing with a topic which could be expanded on at the users leisure outside of reading, without leaving them confused.In particular, the chapters around Scaling, testing and CI deployment really stood out as I have personally had to trawl blog posts and documentation to try and get some of these answers/examples. It is a great time saver to have them clearly laid out in one place and be well written and explained.Who should read this book? developers that are confident with GO fundamentals but are fairly new to micro-services and their implementation. Also, if you currently have one or more projects that use Gin but feel you need greater guidance past the general documentation, it's a great companion.
Amazon Verified review Amazon
Fabrizio G. Jul 26, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I choose this book only to learn something more about the Gin web framework, to use for an API project. What I found in the book, is not only a deep and complete guide to Gin but also a full tutorial on how to create an API from A to Z. It describes you how to create an API, how to connect it to a database, how to properly write and maintain its documentation using Swagger, caching with Redis, authentication with JWT... in order words, it will teach you everything you need to know to build you next API.
Amazon Verified review Amazon
Anshul Jul 28, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nice book for beginners as well for experienced developers to quickly grasp content. What I particularly found useful is, I can read it as a reference at one place, combined with various examples from many sources. So I don't have to read 50 topics at so many place but this concise book is the best reference material at one place. Printing quality, examples and chronological order of content is excellent.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.