Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Building Distributed Applications in Gin

You're reading from   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
Product type Paperback
Published in Jul 2021
Publisher Packt
ISBN-13 9781801074858
Length 482 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Mohamed Labouardy Mohamed Labouardy
Author Profile Icon Mohamed Labouardy
Mohamed Labouardy
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

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

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!

You have been reading a chapter from
Building Distributed Applications in Gin
Published in: Jul 2021
Publisher: Packt
ISBN-13: 9781801074858
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime