doufu1950 2017-01-01 13:58
浏览 87

在Echo golang中使用http标头时,分配给nil映射中的条目

here is my test using testing package and echo web http framework : (webserver variable is a global echo instance)

func TestRunFunction(t *testing.T){
    req := new(http.Request)
    **req.Header.Set("Authorization","Bearer "+loginToken.Token)**
    rec := httptest.NewRecorder()
    c := WebServer.NewContext(standard.NewRequest(req, WebServer.Logger()), standard.NewResponse(rec, WebServer.Logger()))
    c.SetPath(path)
    if assert.NoError(t , RunFunction(c)){
        assert.Equal(t,http.StatusOK, rec.Code)
    }
}

Im trying to test some function that called by REST GET method, but I get this panic error :

panic: assignment to entry in nil map [recovered]
        panic: assignment to entry in nil map

The panic is on the line in bold (astrix in the code), when Im trying to set the header. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dpj0015 2017-01-01 14:39
    关注

    The error is self explanatory: req.Header is nil; you cannot assign to a nil map.

    The solution is to either:

    1. Initialize req.Header with a new instance of net/http.Header

      req.Header = make(http.Header)
      
    2. Or, create the req variable with net/http.NewRequest, which does all the internal initializing for you:

      req, err := http.NewRequest("GET", "https://example.com/path", nil)
      if err != nil {
          panic(err)
      }
      req.Header.Set("Authorization","Bearer "+loginToken.Token)
      
    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测