gocommon/ginutils/requestid.go
Matthieu 'JP' DERASSE 959f245c01
All checks were successful
continuous-integration/drone/push Build is passing
feat(ginutils): Add ginutils that is a toolbox for gin gonic
2023-08-11 18:39:40 +00:00

27 lines
730 B
Go

package ginutils
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// RequestID is a middleware that will get the request_id from the incoming request if exist and
// add it to the response or generate a new ID.
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
requestID := c.GetHeader(string(HeaderKey_RequestID))
if _, err := uuid.Parse(requestID); err != nil {
// no request ID or invalid. let's generate a new one
requestID = uuid.New().String()
}
// Adding to context
c.Set(string(ContextKey_RequestID), requestID)
// Add request-id to the header before sending the response
c.Header(string(HeaderKey_RequestID), requestID)
// Let's the next part run
c.Next()
}
}