我正在try 使用Golang的两个通道来构建接收方和发送方模式.我正在执行一项任务(API调用),并接收回一个Response
struct .我的目标是,当收到响应时,我希望将其发送到另一个通道(writeChan
)进行额外处理.
我想在接收器通道(respChan
)上连续阅读/收听,并处理通过的任何内容(例如Response
).然后,我想启动一个线程,在另一个Goroutine中使用该响应执行进一步的操作.
我想了解如何将此模式链接在一起,以允许数据从API调用流出并并发写入(每个响应都将写入一个单独的文件目的地,由Write()
函数处理).
从本质上讲,我目前的模式如下:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
respChan := make(chan Response) // Response is a struct that contains API response metadata
defer close(respChan)
// requests is just a slice of requests to be made to an API
// This part is working well
for _, req := range requests {
wg.Add(1)
go func(r Request) {
defer wg.Done()
resp, _ := r.Get() // Make the API call and receive back a Response struct
respChan <- resp // Put the response into our channel
}(req)
}
// Now, I want to extract the responses as they become available and send them to another function to do some processing. This I am unsure of how to handle properly
writeChan := make(chan string)
defer close(writeChan)
select {
case resp := <-respChan: // receive from response channel
go func(response Response) {
signal, _ := Write(response) // Separate func to write the response to a file. Not important here in this context.
writeChan <- signal // Put the signal data into the channel which is a string file path of where the file was written (will be used for a later process)
}(resp)
case <-time.After(15 *time.Second):
fmt.Println("15 seconds have passed without receiving anything...")
}
wg.Wait()
}