gocommon/ginutils/requestid.go
Matthieu 'JP' DERASSE 77b4351ef1
All checks were successful
continuous-integration/drone/push Build is passing
feat(error): Create api error. WIP
2023-08-22 19:59:44 +00:00

28 lines
807 B
Go

package ginutils
import (
"git.dev.m-and-m.ovh/mderasse/gocommon/constant"
"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(constant.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(constant.ContextKey_RequestID), requestID)
// Add request-id to the header before sending the response
c.Header(string(constant.HeaderKey_RequestID), requestID)
// Let's the next part run
c.Next()
}
}