Log Requests and Responses in Go-Gin!
Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Search for a command to run...
Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
No comments yet. Be the first to comment.
Move beyond traditional RESTful thinking. Learn how to design APIs specifically for MCP (Model Context Protocol) servers. This guide covers the shift in mindset, a practical OpenAPI 3.1 example, and a Spring Boot implementation to make your services ...

Extending Kestra to Every Corner of Your Data Stack. Introduction: The Power of Plugins Imagine you're a master chef. You don't just have one knife - you have specialized tools for every task: a paring knife for delicate work, a chef's knife for chop...
Mastering Complex Orchestration Scenarios. Introduction: The Orchestrator's Toolkit Imagine you're conducting a symphony. You don't just wave your baton - you cue sections, adjust tempo, handle surprises, and ensure harmony. That's what advanced work...
From Data Extraction to Loading - A Practical Guide Introduction: Why ETL Still Matters in the Modern Data Stack Remember when data engineering was "extract, transform, load"? Some say ETL is dead, replaced by ELT, reverse ETL, and data mesh. But her...
Building Blocks of Declarative Orchestration. Introduction: The Power of Simplicity Imagine trying to build a house without understanding bricks, beams, and blueprints. That's what using an orchestration tool without understanding its core concepts f...

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.
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/.
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.
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://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA
\==========================**=========================
If this article adds any value to you then please clap and comment.
Let’s connect on Stackoverflow, LinkedIn, & Twitter.