Assignment to entry in nil map when using http header with Echo golang

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

Assignment to entry in nil map when using http header with Echo golang

问题

这是我使用测试包和Echo Web HTTP框架进行测试的代码:
(webserver变量是一个全局的Echo实例)

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)
    }
}

我试图测试一个由REST GET方法调用的函数,但是我得到了这个恐慌错误:

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

这个恐慌错误发生在加粗的那一行(代码中的星号),当我尝试设置头部时。我做错了什么?

英文:

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

得分: 10

错误很明显:req.Header 是空的,你不能给一个空的 map 赋值。

解决方法有两种:

  1. 使用 net/http.Header 的新实例初始化 req.Header

     req.Header = make(http.Header)
    
  2. 或者,使用 net/http.NewRequest 创建 req 变量,它会为你进行内部初始化:

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

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)
    

huangapple
  • 本文由 发表于 2017年1月1日 21:58:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/41416017.html
匿名

发表评论

匿名网友

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

确定