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

使用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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)