在中间件中使用*http.request传递上下文会导致错误。

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

Passing context in *http.request in middleware gives an error

问题

我正在尝试通过 chi 中间件将一些数据传递给处理程序函数,代码如下所示:

ctx := context.WithValue(context.Background(), int32(0), company)
next.ServeHTTP(w, r.WithContext(ctx))
return

但是 next.ServeHTTP() 抛出了以下错误:

interface conversion: interface {} is nil, not *chi.Context
英文:

I am trying to pass some data to handler function through a chi middleware like this:

ctx := context.WithValue(context.Background(), int32(0), company)
next.ServeHTTP(w, r.WithContext(ctx))
return

But the next.ServeHTTP() throws this error:

interface conversion: interface {} is nil, not *chi.Context

答案1

得分: 1

context.Background()返回一个非nil的上下文,这就是为什么会出现“interface{}为nil”的错误。你需要更新请求中嵌入的上下文。尝试使用以下代码:

ctx := context.WithValue(r.Context(), int32(0), company)
next.ServeHTTP(w, r.WithContext(ctx))
return
英文:

context.Background() gives a non-nil context and that's why the interface{} is nil error is arising. You need to use update the context embedded in request itself. Try this:

ctx := context.WithValue(r.Context(), int32(0), company)
next.ServeHTTP(w, r.WithContext(ctx))
return

huangapple
  • 本文由 发表于 2022年8月17日 15:15:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/73384260.html
匿名

发表评论

匿名网友

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

确定