Skip to content

Feature: always use context when provided #1886

@ccoVeille

Description

@ccoVeille

There are often the following pattern in the code

func Whatever(foo, bar)
func WhateverContext(ctx context.Context, foo, bar)

the code used in Whatever calls WhateverContext with a new context.

func Whatever(foo, bar) {
   return WhateverContext(context.Background(), foo, bar)
}

It's a very common pattern in Go. Often when lib was created before Go context.Context became that central.

Unfortunately, some low level lib uses the context for some OS, but not for the others.

So sometimes, the context is not used at all in the WhateverContext methods.

This is wrong according to me.

Having With'ontext functions that ignore context cancelation/expiratio sounds like a bug.

I feel like these methods should be updated so the context is at least used.

func WhateverContext(ctx context.Context) error {
   if err := ctx.Err() ; err != nil {
      return err
   }

   // existing code
}

This implementation is naive, something better should be used, that will return the context.Error when the context is canceled.

So something like this maybe better

func WhateverContext(ctx context.Context) error {
   var errChan <- error
   go func() {
       // existing code
      
       errChan <- err
   }

   select {
       case <-ctx.Done():
          return ctx.Err()
       case err <- errChan:
          return err
   }
}

Note here code I provided is naive, and almost pseudo code I wrote for understanding purposes, it has to be rewritten

Originally posted by @ccoVeille in #1883 (comment)

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