2fas-server/internal/common/http/request.go

55 lines
1.1 KiB
Go
Raw Normal View History

2022-12-31 10:22:38 +01:00
package http
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
2023-01-30 19:59:42 +01:00
"github.com/twofas/2fas-server/internal/common/logging"
"net/http"
2022-12-31 10:22:38 +01:00
)
const (
RequestIdKey = "request_id"
CorrelationIdKey = "correlation_id"
CorrelationIdHeader = "X-Correlation-ID"
)
var (
RequestId string
CorrelationId string
)
func RequestIdMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
RequestId = uuid.New().String()
c.Set(RequestIdKey, RequestId)
logging.WithDefaultField(RequestIdKey, RequestId)
}
}
func CorrelationIdMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set(CorrelationIdKey, uuid.New().String())
CorrelationId = c.Request.Header.Get(CorrelationIdHeader)
if CorrelationId == "" {
CorrelationId = uuid.New().String()
}
logging.WithDefaultField(CorrelationIdKey, CorrelationId)
c.Set(CorrelationIdKey, CorrelationId)
}
}
func BodySizeLimitMiddleware(requestBytesLimit int64) gin.HandlerFunc {
return func(c *gin.Context) {
var w http.ResponseWriter = c.Writer
c.Request.Body = http.MaxBytesReader(w, c.Request.Body, requestBytesLimit)
}
}