How to handle per-request context with net/http

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

How to handle per-request context with net/http

问题

这是要翻译的内容:

这个答案的前半部分展示了一种在两个处理程序方法之间共享一些每个请求上下文的模式。有点类似。

我正在寻找一种方法,可以在不止两个处理程序的情况下实现类似的功能。

想象一下,我需要调用三个(或更多)具有相同每个请求上下文的http.HandlerFunc

  • Auth()
  • DoStuff()
  • OutputHTML()

在不使用全局映射(例如gorilla/mux)的情况下,是否有一种方法可以在这些函数之间传递每个请求的上下文,使用标准的http.Handler接口?

英文:

The first half of this answer demonstrates a pattern for sharing some per-request context between two handler methods. Sort of.

I'm looking for a way to do basically this, but with more than two handlers.

Imagine I need to call three (or more) http.HandlerFuncs with the same per-request context:

  • Auth()
  • DoStuff()
  • OutputHTML()

Without resorting to a global map (e.g. gorilla/mux), is there any way, using the standard http.Handler interface, to pass per-request context between these functions?

答案1

得分: 1

你可以通过欺骗和包装Request.Body(一个ReaderCloser接口)来使用你的上下文。

这里有一个例子:webctx.go

当你想要使用你的上下文时,只需断言request.Body为你的类型。
唯一的技巧是你的类型必须保存原始的body并实现ReaderCloser方法...但这只需要很少的代码。

英文:

You can cheat and wrap the Request.Body (a ReaderCloser interface) with your context.

Here's an example: webctx.go

when you want your context, just type assert request.Body to be your type.
Only trick is your type must hold the original body and implement the ReaderCloser methods... but that's a minimal amount of code.

huangapple
  • 本文由 发表于 2015年8月11日 07:26:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/31930782.html
匿名

发表评论

匿名网友

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

确定