...

Source file src/edge-infra.dev/pkg/edge/api/middleware/request.go

Documentation: edge-infra.dev/pkg/edge/api/middleware

     1  package middleware
     2  
     3  import (
     4  	"bytes"
     5  	"net/http"
     6  	"time"
     7  
     8  	"edge-infra.dev/pkg/lib/fog"
     9  
    10  	"github.com/gin-gonic/gin"
    11  	"github.com/go-logr/logr"
    12  )
    13  
    14  // requestMiddleware is an object that holds a gin response writer for http responses, as well as the logger and request body information
    15  type requestMiddleware struct {
    16  	gin.ResponseWriter
    17  	logger logr.Logger
    18  	body   *bytes.Buffer
    19  }
    20  
    21  // RequestLogger is middleware that sends contextual information to fog's middleware logger
    22  func RequestLogger(l logr.Logger) gin.HandlerFunc {
    23  	return func(c *gin.Context) {
    24  		if c.FullPath() == "/health" || c.Request.Method == http.MethodOptions {
    25  			c.Next()
    26  			return
    27  		}
    28  
    29  		entry := &requestMiddleware{
    30  			ResponseWriter: c.Writer,
    31  			body:           bytes.NewBufferString(""),
    32  		}
    33  
    34  		opID := fog.OperationID(c.Request.Context())
    35  		entry.logger = l.WithValues(fog.OperationFields(opID)...)
    36  		entry.logger = l.WithValues("ip", c.ClientIP())
    37  		c.Request = c.Request.Clone(fog.IntoContext(c.Request.Context(), l))
    38  
    39  		t := time.Now()
    40  		c.Next()
    41  
    42  		//only log request if status is not 200
    43  		if c.Writer.Status() != 200 {
    44  			middlewareContext := &fog.MiddlewareContext{
    45  				Request: c.Request,
    46  				Status:  c.Writer.Status(),
    47  				Size:    c.Writer.Size(),
    48  				Body:    entry.body,
    49  				Time:    time.Since(t),
    50  			}
    51  			fog.MiddlewareLogger(l, middlewareContext)
    52  		}
    53  	}
    54  }
    55  
    56  func SetRequestContext() gin.HandlerFunc {
    57  	return func(c *gin.Context) {
    58  		// Add random operation id to context
    59  		ctx := fog.SetOperationContext(c.Request.Context())
    60  		c.Request = c.Request.WithContext(ctx)
    61  		c.Next()
    62  	}
    63  }
    64  

View as plain text