Follow

Follow

Log Requests and Responses in Go-Gin!

Maheshwar Ligade's photo
Maheshwar Ligade
·May 13, 2023·

3 min read

Play this article

Table of contents

  • Setup
  • Logging Requests and Responses
  • Conclusion

Go Gin Framework is a popular web framework for developing RESTful APIs in Go language. Logging is an important aspect of any application, and it is essential to log incoming requests and outgoing responses for debugging, monitoring, and auditing purposes. In this article, we will see how to log requests and responses in Go Gin Framework.

Setup

Before we dive into the implementation, we need to set up a basic Go Gin application. If you already have a Go Gin application set up, you can skip this section.

First, we need to install the Go Gin Framework:

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

Create a new file called main.go with the following contents:

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()

    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Hello, World!",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

This is a simple Go Gin application that listens on the root URL (/) and returns a JSON response with a message.

Save the file and run the application using the following command:

go run main.go

This will start the application on http://localhost:8080/.

Logging Requests and Responses

To log incoming requests and outgoing responses in Go Gin Framework, we can use middleware. Middleware functions are functions that are executed before or after the main handler function. In our case, we will use middleware to log incoming requests and outgoing responses.

Create a new file called middleware.go with the following contents:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "time"
)

func RequestLogger() gin.HandlerFunc {
    return func(c *gin.Context) {
        t := time.Now()

        c.Next()

        latency := time.Since(t)

        fmt.Printf("%s %s %s %s\n",
            c.Request.Method,
            c.Request.RequestURI,
            c.Request.Proto,
            latency,
        )
    }
}

func ResponseLogger() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("X-Content-Type-Options", "nosniff")

        c.Next()

        fmt.Printf("%d %s %s\n",
            c.Writer.Status(),
            c.Request.Method,
            c.Request.RequestURI,
        )
    }
}

In the above code, we have defined two middleware functions: RequestLogger and ResponseLogger.

The RequestLogger function logs the incoming request by recording the start time, calling c.Next() to execute the handler function, and then calculate the latency of the request by subtracting the start time from the current time.

The ResponseLogger function logs the outgoing response by setting the X-Content-Type-Options header to nosniff, calling c.Next() to execute the handler function, and then print the HTTP status code, request method, and request URI.

Now we need to register these middleware functions with our Go Gin application. Open the main.go file and modify it as follows:

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    // Add logging middleware
    r.Use(RequestLogger())
    r.Use(ResponseLogger())

    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Hello, World!",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}

Now, every time a request is made to our server, the logging middleware function logs the request and response.

Conclusion

In this article, we looked at how to log requests and responses in the Go Gin framework using middleware. By using middleware, we can log requests and responses without modifying the application's business logic, making it easier to debug issues and gain insights into how the application is performing.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this