Created
August 14, 2019 06:59
-
-
Save kcollasarundell/0d7b5bf48431e97e79c0ab3cce13f955 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func aggregate(baseCtx context.Context) { | |
ctx, cancel := context.WithTimeout(baseCtx, 5*time.Second) | |
defer cancel() | |
ch := make(chan *http.Response) | |
var wg *sync.WaitGroup | |
var sources []string | |
for _, src := range sources { | |
wg.Add(1) | |
go func(ctx context.Context, source string) { | |
defer wg.Done() | |
resp, err := makeRequest(ctx, source) | |
if err != nil { | |
// log error | |
} | |
ch <- resp | |
}(ctx, src) | |
} | |
go func(wg *sync.WaitGroup) { | |
wg.Wait() | |
close(ch) | |
}(wg) | |
results := make([]*http.Response, 0, len(sources)) | |
for { | |
select { | |
case resp := <-ch: | |
results = append(results, resp) | |
case <-ctx.Done(): | |
break | |
} | |
} | |
// use results | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i see 2 issues here:
results := make([]*http.Response, 0, len(sources))
and the for is appending into this, which meanslen(sources)
number of elements in this slice will benil
pointers forever and actual response will be added after that.ch
. thefor
loop is collecting it and adding it to theresults
. But problem is, it will keep on doing this (even afterclose(ch)
since reading from a closed channel returns zero-value) untilctx.Done()
returns ..