github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/observability/request_id.go (about)

     1  package observability
     2  
     3  import "context"
     4  
     5  type reqIDKeyType int
     6  
     7  const reqIDKey reqIDKeyType = iota
     8  
     9  // RequestIDToContext puts a request ID to context for future use
    10  func RequestIDToContext(ctx context.Context, requestID string) context.Context {
    11  	if ctx == nil {
    12  		panic("Can not put request ID to empty context")
    13  	}
    14  
    15  	return context.WithValue(ctx, reqIDKey, requestID)
    16  }
    17  
    18  // RequestIDFromContext tries to extract request ID from context if present, otherwise returns empty string
    19  func RequestIDFromContext(ctx context.Context) string {
    20  	if ctx == nil {
    21  		panic("Can not get request ID from empty context")
    22  	}
    23  
    24  	if requestID, ok := ctx.Value(reqIDKey).(string); ok {
    25  		return requestID
    26  	}
    27  
    28  	return ""
    29  }