github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/pkg/buffalotools/requestid_middleware.go (about)

     1  package buffalotools
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/gobuffalo/buffalo"
     7  )
     8  
     9  // NewRequestIDMiddleware returns a middleware that adds a request ID to the
    10  // context. It will first attempt to look if the passed headerkey is set in
    11  // the request headers. If it is not set, it will generate a new UUID and set
    12  // it in the logs.
    13  func NewRequestIDMiddleware(headerKey string) buffalo.MiddlewareFunc {
    14  	return func(next buffalo.Handler) buffalo.Handler {
    15  		return func(c buffalo.Context) error {
    16  			id := c.Request().Header.Get(headerKey)
    17  			if id == "" {
    18  				id = fmt.Sprintf("%s", c.Value("request_id"))
    19  			}
    20  
    21  			c.LogField("request_id", id)
    22  
    23  			return next(c)
    24  		}
    25  	}
    26  }