Matthew Yang
Matthew Yang

Reputation: 625

How to return data to sender of a channel

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?

Upvotes: 1

Views: 731

Answers (1)

Dave C
Dave C

Reputation: 7878

See this answer 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).

Upvotes: 2

Related Questions