Skip to content

ExampleStreamDirector: context.WithCancel() and no cancel?Β #29

Open
@pohly

Description

@pohly

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())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions