Golang how to test handlers which 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)


Gives an error, where tmpl.Execute(w, templateData)

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]
March 23rd 20 at 18:53
1 answer
March 23rd 20 at 18:55
Solution
tmpl, _ := template.ParseFiles("")
You are not check the returned error, and quite logical punch you panic then.

P. S. it is Not necessary to parse the template on each call of the handler. Need to parse it once at application start.
Thanks, and true, when called from the folder to the cmd, everything was OK, and the test in another place altogether. Thank you)

It is not necessary to parse the template on each call of the handler. Need to parse it once at application start


In what place to do this?And then as addiction transfer? - bennett_Beier commented on March 23rd 20 at 18:58
@bennett_Beierdepends on the architecture of your application. Ideally, during the initialization of the package, which is responsible for standardization. Accordingly, rasparennye patterns will lie within that package. - Myriam_Hermann16 commented on March 23rd 20 at 19:01

Find more questions by tags Go