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

3.6k views Asked by At

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

There are 1 answers

0
AudioBubble On

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)