Book Image

Building Distributed Applications in Gin

By : Mohamed Labouardy
4 (1)
Book Image

Building Distributed Applications in Gin

4 (1)
By: Mohamed Labouardy

Overview of this book

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.
Table of Contents (16 chapters)
1
Section 1: Inside the Gin Framework
3
Section 2: Distributed Microservices
9
Section 3: Beyond the Basics

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.