Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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

eBook
€29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
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 golang@1.15.6

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 : 9781801079556
Vendor :
Google
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 111.97
Hands-On RESTful Web Services with Go
€32.99
Mastering Go – Third Edition
€41.99
Building Distributed Applications in Gin
€36.99
Total 111.97 Stars icon

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.