Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

go

go-echo

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?

like image 717
Chenko47 Avatar asked Dec 23 '22 22:12

Chenko47


1 Answers

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)
    
like image 50
Tim Cooper Avatar answered Dec 27 '22 07:12

Tim Cooper