0

When one occur error, how to stop another?

I must use res1 and res2,in production res1, res2 are not same static type.

package main

import (
    "fmt"
    "net/http"
    "sync"
)

func main() {
    wg := &sync.WaitGroup{}
    wg.Add(2)

    var res1, res2 *http.Response
    var err1, err2 error

    go func() {
        defer wg.Done()
        res1, err1 = http.Get("http://127.0.0.1:8899")
        if err1 != nil {
            panic(err1)
        }
    }()
    go func() {
        defer wg.Done()
        res2, err2 = http.Get("http://127.0.0.1:8898")
        if err2 != nil {
            panic(err2)
        }
    }()
    wg.Wait()

    fmt.Println(res1, res2)
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

5

A common context should be able to cancel all waiting requests. Something like this:

ctx, cancel:=context.WithCancel(context.Background())
defer cancel()
cli:=http.Client{}
go func() {
   req:=http.NewRequestWithContext(ctx,http.MethodGet,url,nil)
   respose, err:=cli.Do(req)
   if err != nil {
     cancel()
     return
   }
}()

You should use the same ctx for all http requests, and when one fails, cancel it. Once the context is canceled, all other http requests should cancel as well.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • 1
    In the above example, a new client would be created each time the go-routine is run. Might I suggest, since the OP had two go-routine tasks, to use a common http.Client that is shared. – colm.anseo Nov 15 '19 at 03:59
  • @colminator, thx, moved cli outside the goroutine – Burak Serdar Nov 15 '19 at 04:05