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?
The error is self explanatory: req.Header
is nil; you cannot assign to a nil map.
The solution is to either:
Initialize req.Header
with a new instance of net/http.Header
req.Header = make(http.Header)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With