- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我试图了解 Golang 1.7 中引入的上下文是如何工作的,以及将它传递给中间件和 HandlerFunc
的合适方法是什么。上下文是否应该在主函数中初始化并传递给 checkAuth
函数?以及如何将其传递给 Hanlder
和 ServeHTTP
函数?我读了Go concurrency patterns和 How to use Context但我很难使这些模式适应我的代码。
func checkAuth(authToken string) util.Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Auth") != authToken {
util.SendError(w, "...", http.StatusForbidden, false)
return
}
h.ServeHTTP(w, r)
})
}
}
// Handler is a struct
type Handler struct {
...
...
}
// ServeHTTP is the handler response to an HTTP request
func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
// decode request / context and get params
var p params
err := decoder.Decode(&p)
if err != nil {
...
return
}
// perform GET request and pass context
...
}
func main() {
router := mux.NewRouter()
// How to pass context to authCheck?
authToken, ok := getAuthToken()
if !ok {
panic("...")
}
authCheck := checkAuth(authToken)
// initialize middleware handlers
h := Handler{
...
}
// chain middleware handlers and pass context
router.Handle("/hello", util.UseMiddleware(authCheck, Handler, ...))
}
最佳答案
如果您查看 first example at that Go Concurrency Patterns blog post ,您会注意到它们是从 Background
上下文“派生”它们的上下文。结合 Request
对象上的 Context
和 WithContext
方法,可以满足您的需求。
我刚刚弄明白了(这不是我第一次阅读这些文档);当您“导出”一个上下文时,您正在通过一次更改创建另一个上下文。我已经包装了 http.Handler
(实际上是使用 httprouter.Handle
)。 Request.Context
的妙处在于它永远不会返回 nil
;如果没有创建其他上下文,则返回后台上下文。
要指定超时,在您的处理程序中(就在您的“//执行 GET 请求”评论上方),您可以执行以下操作:
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(60*time.Second))
defer cancel()
r = r.WithContext(ctx)
第一行创建上下文并为您提供取消 Hook ,您可以推迟;一旦请求得到服务,执行此延迟调用(第 2 行)时,任何派生上下文(也就是您添加变量的上下文)都将被取消。最后,第 3 行替换了请求,该请求现在包含更新后的上下文。
在您的授权检查器中,一旦确定用户有效,就可以在调用 ServeHTTP
之前将用户信息添加到上下文中。上下文的键不能使用内置类型,但您可以创建一个新类型,它只是内置类型的别名。为您的键值定义常量也是一个好主意。一个例子:
type ContextKey string
const ContextUserKey ContextKey = "user"
// Then, just above your call to ServeHTTP...
ctx := context.WithValue(r.Context(), ContextUserKey, "theuser")
h.ServeHTTP(w, r.WithContext(ctx))
这会将现在两次派生的上下文(现在具有超时和用户 ID)传递给处理程序。
最后,拼图的最后一 block - 如何从处理程序中获取用户 ID。这是最直接的部分;我们只需对从请求的 Context
方法返回的值使用 Value
方法。类型是 interface{}
,因此如果您想将其视为字符串(如本例所示),则需要类型断言。
user := r.Context().Value(ContextUserKey)
doSomethingForThisUser(user.(string))
您不限于对每种方法进行一次更改;只要你继续派生相同的上下文,一旦请求被服务,它就会被清理干净,当最初派生的上下文(在这个例子中,我们指定超时的那个)在延迟 cancel()
调用触发。
关于design-patterns - 如何将golang请求中的上下文传递给中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39946583/
我正在尝试运行这段代码,用随机数替换字符串中的一个字符: //Get the position between 0 and the length of the string-1 to insert
我有一个包含 3 个位置的数组,假设它的所有位置都是数字 5。 [5 5 5] 我怎样才能以保持 555 的方式将它传递给 var?就像这样。 n:= 555 最佳答案 与使用任何其他语言的方式相同:
我使用 go dep 工具版本 v0.4.1,现在当我运行 dep init 时它会按预期创建 2 个文件,当我打开 gopkg.lock 我发现例如以下内容 [[projects]] name
我正在制作学习联系申请。我有一个 NewContact()。 // Contact - defines the fields of an entire Contact type Contact str
我一直在尝试使用该模块: https://godoc.org/github.com/hirochachacha/go-smb2#RemoteFile.ReadAt 为了在 Windows 机器上对我的
我需要在 golang 中编译 golang 中的程序。有没有不使用 exec.Command("go","build") 的原生形式? 最佳答案 不幸的是,我认为使用 exec.Command 是利
编写输出有效 go 代码的 go 应用程序可能最好使用内置的“go”包及其一些子包(“go/ast”、“go/token”、“go/printer”、等)。 要创建字符串文字表达式,您需要创建一个 a
我正在尝试使用 Golang 和 gin 为我的 api 和前端编写代理。如果请求转到除“/api”之外的任何内容,我想代理到 svelte 服务器。如果出现“/api/something”,我想在
我偶然发现了这个博客:using go as a scripting language并尝试创建一个可用于运行 golang 脚本的自定义图像,即 FROM golang:1.15 RUN go ge
我刚开始接触golang,我需要从json字符串中获取数据。 {"data" : ["2016-06-21","2016-06-22","2016-06-25"], "sid" : "ab", "di
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 3 年前。 Improve
我是 goland 的新手,试图在我的第一个项目中使用它。我注意到在 goland 中它没有显示通过容器引入的相同 golang SDK。 这是我的 Dockerfile: FROM golang:1
我正在试用 golang-neo4j-bolt-driver 包 github.com/johnnadratowski/golang-neo4j-bolt-driver 我已经导入了包并正在使用创建新
如果我安装了Go发行版软件包,则会在/usr/lib/golang/pkg中看到很多文件,在/usr/lib/golang/src中看到非常相似的文件集。这两组之间有什么关系? pkg是从src中的源
我发现 golang 上下文对于在客户端-服务器请求范围内取消服务器的处理很有用。 我可以使用 http.Request.WithContext 方法发出带有上下文的 http 请求,但是如果客户端不
我正在尝试将一个 golang 数组(还有 slice、struct 等)放置到 HTML 中,这样当从 golang gin web 框架返回 HTML 时,我可以在 HTML 元素内容中使用数组元
目前正在使用这个 ffmpeg 命令编辑视频 ffmpeg -i "video1.ts" -c:v libx264 -crf 20 -c:a aac -strict -2 "video1-fix.ts
我需要从 play.golang.org 链接读取 golang 代码并保存到 .go 文件。我想知道 play.golang.org 是否有任何公共(public) API 支持。我用谷歌搜索但没有
我第一次使用 IntelliJ 的最新 (2014-01-03) Golang 插件。 通常,我的终端工作流程是 go build && ./executable -args=1 所以我试图创建一个启
这个问题只是在构建之间随机出现,现在甚至我们的生产 repo,几个月都没有改变,在构建时也会出现这个问题。我已经坚持了一段时间。它不会发生在我们的本地机器上,只有在使用 dockerfile 时才会发
我是一名优秀的程序员,十分优秀!