github.com/hanks177/podman/v4@v4.1.3-0.20220613032544-16d90015bc83/pkg/api/server/handler_rid.go (about)

     1  package server
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"net/http"
     7  
     8  	"github.com/hanks177/podman/v4/pkg/api/types"
     9  	"github.com/google/uuid"
    10  	"github.com/gorilla/handlers"
    11  	"github.com/gorilla/mux"
    12  	"github.com/sirupsen/logrus"
    13  )
    14  
    15  // referenceIDHandler adds X-Reference-Id Header allowing event correlation
    16  // and Apache style request logging
    17  func referenceIDHandler() mux.MiddlewareFunc {
    18  	return func(h http.Handler) http.Handler {
    19  		// Only log Apache access_log-like entries at Info level or below
    20  		out := ioutil.Discard
    21  		if logrus.IsLevelEnabled(logrus.InfoLevel) {
    22  			out = logrus.StandardLogger().Out
    23  		}
    24  
    25  		return handlers.CombinedLoggingHandler(out,
    26  			http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    27  				rid := r.Header.Get("X-Reference-Id")
    28  				if rid == "" {
    29  					if c := r.Context().Value(types.ConnKey); c == nil {
    30  						rid = uuid.New().String()
    31  					} else {
    32  						rid = fmt.Sprintf("%p", c)
    33  					}
    34  				}
    35  
    36  				r.Header.Set("X-Reference-Id", rid)
    37  				w.Header().Set("X-Reference-Id", rid)
    38  				h.ServeHTTP(w, r)
    39  			}))
    40  	}
    41  }