如何 return 数据到频道的发送者
How to return data to sender of a channel
我是 Golang 新手,我正在尝试实现一个 http 服务器,该服务器使用通道同步对超昂贵计算 (SAT) 操作的访问。
所以我会收到这些并发请求,它们会将数据传递到通道,然后处理 goroutine 会从通道中获取数据并执行昂贵的操作,但完成后,会发生什么return 将结果发送给发件人以便发件人可以发送 http 响应的最佳方式是什么?
另见 this answer。
通道是 Go 中的第一个 class 类型,
您可以在请求本身中包含一个 "response" 频道。
例如。类似于:
type Request struct {
Input int
RespC chan *Responce
}
type Response struct {
Result int
Err error
}
服务:
for req := range ReqC {
// start go routine or whatever
req.RespC <- &Result{Err: errors.New("not implemented")}
}
请求者:
c := make(chan *Response)
ReqC <- &Request{Input: 42, RespC: c}
res := <-c
// check res.Err, use res.Result
其中 Request
和 Response
可以包含您需要的任何字段。
如果结构很小(如本例),请使用 chan Response
而不是 chan *Response
(Request
也是如此)。
我是 Golang 新手,我正在尝试实现一个 http 服务器,该服务器使用通道同步对超昂贵计算 (SAT) 操作的访问。
所以我会收到这些并发请求,它们会将数据传递到通道,然后处理 goroutine 会从通道中获取数据并执行昂贵的操作,但完成后,会发生什么return 将结果发送给发件人以便发件人可以发送 http 响应的最佳方式是什么?
另见 this answer。
通道是 Go 中的第一个 class 类型, 您可以在请求本身中包含一个 "response" 频道。 例如。类似于:
type Request struct {
Input int
RespC chan *Responce
}
type Response struct {
Result int
Err error
}
服务:
for req := range ReqC {
// start go routine or whatever
req.RespC <- &Result{Err: errors.New("not implemented")}
}
请求者:
c := make(chan *Response)
ReqC <- &Request{Input: 42, RespC: c}
res := <-c
// check res.Err, use res.Result
其中 Request
和 Response
可以包含您需要的任何字段。
如果结构很小(如本例),请使用 chan Response
而不是 chan *Response
(Request
也是如此)。