Created
May 29, 2020 14:48
-
-
Save RicardoLinck/5e0ee76adfa214137fc00fc5cf1a3404 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
package main | |
import ( | |
"math/rand" | |
"sync" | |
"time" | |
"github.com/google/uuid" | |
) | |
type externalData struct { | |
inputData | |
// fields fetched from external service | |
relatedIds []string | |
} | |
func fetchData(ic <-chan inputData) <-chan externalData { | |
oc := make(chan externalData) | |
go func() { | |
wg := &sync.WaitGroup{} | |
for input := range ic { | |
wg.Add(1) | |
go fetchFromExternalService(input, oc, wg) | |
} | |
wg.Wait() | |
close(oc) | |
}() | |
return oc | |
} | |
func fetchFromExternalService(input inputData, output chan<- externalData, wg *sync.WaitGroup) { | |
// emulates an http request | |
time.Sleep(time.Duration(rand.Intn(50)) * time.Millisecond) | |
related := make([]string, 0) | |
for i := 0; i < rand.Intn(10); i++ { | |
related = append(related, uuid.New().String()) | |
} | |
output <- externalData{input, related} | |
wg.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment