I have a logging interceptor for my grpc server and want to add a value to the metadata (I want to track the request throughout its lifetime):
func (m *middleware) loggingInterceptor(srv interface{},
ss grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler)
md, ok := metadata.FromIncomingContext(ss.Context())
if !ok {
return errors.New("could not get metadata from incoming stream context")
}
// add the transaction id to the metadata so that business logic can track it
md.Append("trans-id", "some-transaction-id")
// call the handler func
return handler(srv, ss)
}
but the docs for FromIncomingContext
state that:
// FromIncomingContext returns the incoming metadata in ctx if it exists. The
// returned MD should not be modified. Writing to it may cause races.
// Modification should be made to copies of the returned MD.
Ok, so I look at the copy function and copy the metadata:
mdCopy := md.Copy()
mdCopy.Append("trans-id", "some-transaction-id")
and think "how do I attach this metadata back to the ServerStream
context?", and I check if there's some ss.SetContext(newCtx)
, but I don't see anything of the sort. Am I thinking about this from the wrong perspective, or am I missing something else?