ExampleStreamDirector: context.WithCancel() and no cancel?
pohly opened this issue · comments
Patrick Ohly commented
go vet
warns about ignoring the cancel function returned by context.WithCancel():
func ExampleStreamDirector() {
director = func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {
// Make sure we never forward internal services.
if strings.HasPrefix(fullMethodName, "/com.example.internal.") {
return nil, nil, grpc.Errorf(codes.Unimplemented, "Unknown method")
}
md, ok := metadata.FromIncomingContext(ctx)
// Copy the inbound metadata explicitly.
outCtx, _ := context.WithCancel(ctx)
outCtx = metadata.NewOutgoingContext(outCtx, md.Copy())
https://stackoverflow.com/questions/44393995/what-happens-if-i-dont-cancel-a-context explains that this leads to a resource leak.
What is the purpose of creating two contexts (first with context.WithCancel, then with metadata.NewOutgoingContext)? To me it looks like the first one is simply redundant and the code can be simplified to:
// Copy the inbound metadata explicitly.
outCtx := metadata.NewOutgoingContext(ctx, md.Copy())