How to implement a retry mechanism for goroutines?

Viewed 372

new to working with goroutines; currently have a really simple implementation of:

func someFunc() error {
  resp, err := httpClient.Post()
  if err != nil {
    log...
    return error
  }

  return nil
}

func flowA() {
  ...

  go someFunc()
}

What I'd like to achieve is to implement retrying on unsuccessful response from the Post request inside of the func being managed by the goroutine. Not sure if it's better to handle the retry logic by wrapping the someFunc() err value, or if there's a more idiomatic way to handle errors returned within a goroutine.

1 Answers

One way to have a retry mechanism is this, here I am retrying for a max of n=5 times, based on the status code we can also have a check to retry only if response status code is 4XX

 func someFunc(maxRetry int) error {
      maxRetry = maxRetry - 1
      resp, err := httpClient.Post()
      if resp.StatusCode != http.StatusOK {
          if maxRetry > 0 {
            return someFunc(maxRetry)
          }
      }
        
      if err != nil {
        log...
        return error
      }
    
      return nil
    }
    
    func flowA() {
      ...
    
      go someFunc(5)
    }
Related