Golang Gin framework – create a golang microservice

Gin-gonic/gin is a popular web framework in Golang that I’m using a lot lately. This became my goto framework when I work with microservices in golang. Hence, I decided to write a blog post to share what I learnt on creating a microservice in golang using the gin framework.

A brief intro to gin framework

What is gin?

Gin-gonic/gin is a golang fully-featured, highly performant web framework popular among go developers. It helps us in developing web applications without much boiler plate codes. Checkout their Github repository to know more.

Why gin?

  • It is fully-featured – The gin ecosystem provides every features required to develop a web application.
  • It is highly performant – Gin uses a custom implementation of httprouter making it highly performant and lightweight. You can read the httprouter documentation to know further. Checkout the gin’s benchmarks.
  • Gin has a great community support. You can find a variety of middlewares contributed by open source contributors.

Project setup

Let’s start with the project setup before creating the web application.

Golang installation

If you haven’t installed Go yet, follow the steps provided here. Note that gin requires go version 1.15+.

Create a Go module

If you are new to Golang, this official documentation provides full information on how to create a go module.

I started by creating a github repo go-gin-example and I’ll be committing the example code of this blog post here. Then I checked out this repo in my local, opened the repo in VS Code and created a go module by executing the below command.

go mod init github.com/GeekSpotlight/go-gin-example

This generates a go.mod file. Now it’s time to create a go file with the entry point main function.

package main
import "fmt"
func main() {
    fmt.Println("I'm alive!")
}

On executing this, you should get the line printed.

$ go run main.go 
I'm alive!

Installing gin-gonic/gin

Now that we have created a project for our microservice, let’s install gin. The below command does the trick.

go get -u github.com/gin-gonic/gin

You can find the go.mod file updated with the dependencies.

Creating the microservice using gin

A router is all you need to setup a Go microservice with gin.

Creating router

Now that we have installed gin, let’s create our first router.

What is routing?

Before creating a router, let’s see what is routing. In a web application, routing is a mechanism by which the application knows which code handles the HTTP request. Let’s say I want my application to provide two APIs /hi and /bye. For this, I would require the business logic to compute a response and a router. Here the router will route the API requests to the respective business logic methods. This mechanism is routing.

routing example for golang gin framework
The process of routing

Adding the routes

I have updated main.go with three routes /health, /hi and /bye. The below is the updated code.

package main
import (
    "github.com/gin-gonic/gin"
)
func main() {
    router := gin.New()
    // serves http://localhost:8080/health
    router.GET("/health", func(ctx *gin.Context) {
        ctx.String(200, "I'm alive!")
    })
    // http://localhost:8080/hi
    router.GET("/hi", func(ctx *gin.Context) {
        ctx.String(200, "hello there!")
    })
    // http://localhost:8080/bye
    router.GET("/bye", func(ctx *gin.Context) {
        ctx.String(200, "take care now")
    })
    // by default, runs in port :8080
    router.Run()
}

Let’s dissect the code line by line.

The statement router := gin.New() will create a new gin router. The syntax for creating a route is router.<HTTP_METHOD>("<API_PATH>", <CALL_BACK_FUNCTION>).

  • HTTP_METHOD – this describes the type of API’s HTTP method. Basically, router provides functions with same name same as the HTTP method type of the request. This makes things easier for us.
  • API_PATH – the path of the API. This is the API requested by the client.
  • CALL_BACK_FUNCTION – a callback function that handles the request. This function should be of type gin.HandlerFunc.

The callback function is of type gin.HandlerFunc which takes *gin.context as parameter. gin.context is an important part of gin framework which helps in validating request, generating response and passing data between middlewares. The statement ctx.String(200, "hello there!") generates a text/plain response with HTTP status code 200.

Optionally, you can use net/http package to make use of the HTTP status code constants. Replace the hardcoded 200 with http.StatusOK as below. Make sure you import net/http package.

ctx.String(http.StatusOK, "hello there!")

The statement router.Run() attaches the router with http.Server and starts to serve the API routes. By default, Run() will listen to port 8080. If you need a different port, you can use router.Run(":<PORT_NUM>"). If I want the application to serve in port 5001, then I have to use the statement router.Run(":5001").

Finally, now that we have created the routes, let’s start the application. Execute the command go run main.go and hit up http://localhost:8080/hi to say hi.

gin.New vs gin.Default

Routers can be initialized in two ways, by using gin.New() and gin.Default(). In the above example, we used gin.New() to create the router engine. Let’s see the difference.

gin.New

gin.New() creates a blank engine with default settings. Default configuration is as below.

  • RedirectTrailingSlash:  true
  • RedirectFixedPath:      false
  • HandleMethodNotAllowed: false
  • ForwardedByClientIP:    true
  • UseRawPath:             false
  • UnescapePathValues:     true

Source code can be found here.

gin.Default

gin.Default() uses gin.New() internally to create an engine. Additionally it adds logger and recovery middlewares. Source code can be found here. I will cover about middlewares in a separate post.

Conclusion

Now, we have created a simple go web application using gin. Let’s add more features to this application in future posts. The source code can be found in this Github repository.


I hope this post was helpful 😊. If you find this post informative, support us by sharing this with fellow programmers in your circle 😀.

For any suggestions, improvements, reviews or if you like us to cover a specific topic, please leave a comment.
Follow us on twitter @thegeeksclan and in Facebook.
#TheGeeksClan #DevCommunity

error

Enjoy this blog? Please spread the word :)