douguyi3903 2016-08-25 09:17
浏览 682
已采纳

如何将值从一个handlerFunc传递给另一个go-gin

I have rest API defined as

    apis.GET(/home, validatationHandler , dashboardHandler)

I want pass some data from validatationHandler to dashboardHandler. For this I thought of using header. To set the data I use this in validatationHandler

    c.Writer.Header().Set("myheader", "mytoken")
    c.Next()

and in dashboardHandler I tried to access it using

fmt.Println(c.Request.Header.Get("myheader"))

But the value is always nil. Any idea how can I set and retrieve headers? Is there any other way I can pass on the data from 1 handler to another?

  • 写回答

1条回答 默认 最新

  • drny60365 2016-08-25 09:24
    关注

    You can pass values via gin.Context Use ctx.Set(k, v) in fisrt one and ctx.Get(k) in the next.

    So How to Use It:

    ctx.Set("myKey", 100)
    

    and get it using

    v, ok := ctx.Get("myKey")
    if ok {
       actualValue := v.(int) // you need to type convert it as it returns interface.
    }
    

    See context.go

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序