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

Exploring MongoDB queries

In this section, we will interact with the MongoDB server using CRUD operations, but first, let's create a database where the API data will be stored.

Note

You can view the full documentation for the MongoDB Go driver on the GoDoc website (https://godoc.org/go.mongodb.org/mongo-driver).

The InsertMany operation

Let's initialize the database with the recipes.json file we created in the previous chapter. First, retrieve a Database and then a Collection instance from Client. The Collection instance will be used to insert documents:

func init() {
   recipes = make([]Recipe, 0)
   file, _ := ioutil.ReadFile("recipes.json")
   _ = json.Unmarshal([]byte(file), &recipes)
   ctx = context.Background()
   client, err = mongo.Connect(ctx, 
       options.Client().ApplyURI(os.Getenv("MONGO_URI")))
  &...