Complete http.Request asynchronously in Golang

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

Complete http.Request asynchronously in Golang

问题

我想将所有到达的http.Request放入一个队列中,并有一个单独的线程(goroutine?)处理这些请求并返回适当的状态。

然而,即使http.Request对象异步发送到goroutine,主http request处理程序仍直接完成请求。

有没有办法控制http.Request何时完成,从而异步处理它?

[更新]

我想实现一个生产者-消费者模型。主请求处理程序生成请求并将它们放入队列中。一个消费者线程(或多个线程)将读取这些请求,消费请求的主体并返回它们。

英文:

I want to put all arriving http.Requests into a queue and have a separate thread (goroutine?) process these requests and return the appropriate status.

However, the main http request handler directly completes the request even when the http.Request object is sent asynchronously to a goroutine.

Is there a way to control when the http.Request is completed and thereby asynchronously process it?

[Update]

I want to implement a producer-consumer model. The main request handler produces the requests and put them into a queue. A consumer thread (or threads) will read these requests, consume the body of the requests and return them.

答案1

得分: 1

http处理程序在每个请求中都在不同的goroutine中执行,因此如果你只是想释放主要的服务循环,这是不必要的。

如果你想对请求进行序列化处理,可以使用sync.Mutex并让处理程序在其上加锁。这样做会有类似的效果,即请求会逐个处理。

我认为sync.Mutex可能不太适合,所以可能不符合你的需求。

另外,如果你想在请求之间保持状态,那么这可能不是正确的解决方案。

正如Jorge Marey提到的,通道也可以起作用。

不过,我建议你看一下golang.org/x/net/context,因为它是一个专门用于具有超时等多阶段处理的包。

我猜你最终会使用一个传递类似以下结构体的通道:

type Req struct{
   ctx context.Context
   w http.ResponseWriter
   r *http.Request
}
英文:

http handlers are executed in a different goroutine per request, so if you are simply trying to free up the main serve loop, it's not neccesary.

If you are looking to serialize processing of requests, you could use a sync.Mutex and have your handler's lock on that. This would have a similar effect in that the requests would be handled one at a time.

I don't think sync.Mutex is fair, so it may not meet your needs.

also, if you wanted to be stateful between requests, then this is probably not the right solution.

As Jorge Marey mentioned, channels would work as well.

Though, i'd suggest you look at golang.org/x/net/context as it is a package specifically designed for multi-stage processing with timeouts and whatnot.

my guess is you will end up with a channel that passes structs that look like:

type Req struct{
   ctx context.Context
   w http.ResponseWriter
   r *http.Request
}

huangapple
  • 本文由 发表于 2015年10月13日 15:14:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/33096365.html
匿名

发表评论

匿名网友

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

确定