douzi5214
2019-03-01 05:50
浏览 41
已采纳

使用Value(key)后上下文返回nil接口

I have a ctx (context.Context) variable, whose value is:

ctx = context.Background.WithCancel.WithCancel.WithValue(peer.peerKey{}, &peer.Peer{Addr:(*net.UnixAddr)
(0xc000270820), AuthInfo:credentials.AuthInfo(nil)}).WithValue(metadata.mdIncomingKey{}, 
metadata.MD{":authority":[]string{"unix:///run/containerd/containerd.sock"}, "content-type":
[]string{"application/grpc"}, "user-agent":[]string{"grpc-go/1.12.0"}, 
"containerd-lease":[]string{"615343279-BvIN"}, "containerd-namespace":
[]string{"default"}}).WithValue(grpc.streamKey{}, <stream: 0xc00026af00, 
/containerd.services.content.v1.Content/Write>).WithValue(log.loggerKey{}, 
&logrus.Entry{Logger:(*logrus.Logger)(0xc0000b0180), 
Data:logrus.Fields{"ref":"config-
sha256:bc8fb6e6e49dac415b320f3ce41fa4f6335a4526fccd4e97c64bcbdfca280ba5", 
"total":1512, 
"expected":"sha256:bc8fb6e6e49dac415b320f3ce41fa4f6335a4526fccd4e97c64bcbdf
ca280ba5"}, Time:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, 
Level:0x0, Caller:(*runtime.Frame)(nil), Message:"", Buffer:(*bytes.Buffer)
(nil), err:""})

As you can see here, there is a Data field, with some other values. I want to extract the ref value and expected value in Data field. I tried putting them out with Value() field, I always get nil. Any idea how can I get these value out? As far as I understand loggerKey{} is the key here, so I tried to take the data out with loggerKey{} as well, but it still says that the interface is nill.

logger := ctx.Value(loggerKey{}).(*logrus.Entry)

Printing logger throws me the error:

panic: interface conversion: interface {} is nil, not *logrus.Entry

Not sure, why the interface is nil here. TIA.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqx13503925528 2019-03-01 14:31
    已采纳

    Figured it out. I was using loggerKey{} as the key, while the actual key is log.loggerKey{}. I had to import log and then it worked.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题