I am trying to write tests for a simple rest application in go. So I write something like this:
func TestMyTestFunc(t *testing.T) {
var w = httptest.NewRecorder()
req, err := http.NewRequest("POST", "/", nil)
if err != nil {
t.Errorf("Error creating request: %s", err.Error())
}
// req.Header.Add("Content-Type", "application/json")
// req.Header.Add("Accept", "application/json")
l.ServeHTTP(w, req) // l is defined somewhere above
// check for w.Code, w.Body
}
This works perfectly fine. Now I would like to add headers. So I add the commented header part and end up with:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
and the error is on this line: l.ServeHTTP(w, req)
.
Interesting part, that if I set only Content-Type
or Accept
, the test runs, but if I set both, it fails. What's wrong?
P.S. I also tried to use req.Header.Set
, but with no difference. Here is an stub for my handler:
func (l myHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// check for validity
if !valid {
http.Error(w, "Invalid Accept", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
I think error in your http server/handler implementation. I tried to reproduce it and it worked.
You can see here: http://play.golang.org/p/n1YBl3OpbN