英文:
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 赋值。
解决方法有两种:
- 
使用
net/http.Header的新实例初始化req.Header:req.Header = make(http.Header) - 
或者,使用
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:
- 
Initialize
req.Headerwith a new instance ofnet/http.Headerreq.Header = make(http.Header) - 
Or, create the
reqvariable withnet/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) 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论