英文:
How to return data to sender of a channel
问题
我是一个 Golang 新手,我正在尝试使用通道实现一个 HTTP 服务器,该服务器通过通道同步访问一个非常昂贵的计算(SAT)操作。
所以,当并发请求到达时,它们会将数据传递给一个通道,然后一个处理 goroutine 会从通道中获取数据并执行昂贵的操作,但在操作完成后,最好的方法是如何将结果返回给发送者,以便发送者可以发送 HTTP 响应呢?
英文:
I am a Golang newbiew, and I am trying to implement an http server that synchronizes access to an ultra expensive computational (SAT) operation using a channel.
So I'd have these concurrent requests coming in, they'd pass their data to a channel, and a processing goroutine would pick up the data from the channel and perform the expensive operation, but after its done, what is the best way to return the result to the sender so the sender can send the http response?
答案1
得分: 2
请参考这个答案。
在Go语言中,通道是一种一等类型,你可以在请求本身中包含一个"response"通道。例如:
type Request struct {
Input int
RespC chan *Response
}
type Response struct {
Result int
Err error
}
服务端:
for req := range ReqC {
// 启动goroutine或其他操作
req.RespC <- &Response{Err: errors.New("not implemented")}
}
请求端:
c := make(chan *Response)
ReqC <- &Request{Input: 42, RespC: c}
res := <-c
// 检查res.Err,使用res.Result
其中,`Request`和`Response`可以包含你需要的任何字段。如果结构体很小(像这个例子),可以使用`chan Response`代替`chan *Response`(对于`Request`也是一样)。
<details>
<summary>英文:</summary>
See [this answer](https://stackoverflow.com/a/27238300/55504) as well.
Channels are first class types in Go,
you can just include a "response" channel in the request itself.
E.g. something like:
type Request struct {
Input int
RespC chan *Responce
}
type Response struct {
Result int
Err error
}
Service:
for req := range ReqC {
// start go routine or whatever
req.RespC <- &Result{Err: errors.New("not implemented")}
}
Requester:
c := make(chan *Response)
ReqC <- &Request{Input: 42, RespC: c}
res := <-c
// check res.Err, use res.Result
Where `Request` and `Response` can contain whatever fields you need.
If the structs are small (like this example) use `chan Response` instead of `chan *Response` (and the same for `Request`).
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论