How do I implement request ID propagation with Gin in Go?

Implementing Request ID Propagation with Gin in Go

Request ID propagation is a crucial aspect of distributed systems that helps track requests across various services. In Go, using the Gin web framework, you can easily implement this feature to enhance observability and logging.

Keywords: Go, Gin, Request ID, Propagation, Distributed Systems
Description: Learn how to implement request ID propagation in Go using Gin framework for better tracking and logging of requests in distributed systems.

package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/google/uuid"
)

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

    // Middleware to generate and propagate request ID
    r.Use(func(c *gin.Context) {
        requestID := c.Request.Header.Get("X-Request-ID")
        if requestID == "" {
            requestID = uuid.New().String() // Generate new UUID if not provided
        }
        c.Set("RequestID", requestID)
        c.Header("X-Request-ID", requestID) // propagate response header
        c.Next()
    })

    r.GET("/example", func(c *gin.Context) {
        requestID := c.MustGet("RequestID").(string)
        c.JSON(http.StatusOK, gin.H{
            "message":    "Hello, World!",
            "request_id": requestID,
        })
    })

    r.Run()
}
    

Keywords: Go Gin Request ID Propagation Distributed Systems