Answer the question
In order to leave comments, you need to log in
Golang how to test handlers that return a template?
func (c Controller) Index(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("")
_ = tmpl.Execute(w, templateData)
}
req, _ := http.NewRequest("GET", "/sites", nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(controller.Index)
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x595bfe]
Answer the question
In order to leave comments, you need to log in
tmpl, _ := template.ParseFiles("")
You do not check the returned error here and it is quite logical to panic later.
PS You shouldn't parse the template every time the handler is called. It must be parsed once at the start of the application.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question