如何将数据返回给通道的发送者?

huangapple go评论80阅读模式
英文:

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 &quot;response&quot; channel in the request itself.
E.g.&#160;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 &lt;- &amp;Result{Err: errors.New(&quot;not implemented&quot;)}
    }
    
Requester:

    c := make(chan *Response)
    ReqC &lt;- &amp;Request{Input: 42, RespC: c}
    res := &lt;-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>



huangapple
  • 本文由 发表于 2015年4月6日 10:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/29464686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定