go - Idiomatic way to handle template errors in golang -


say have html/template following:

<html> <body>     <p>{{somefunc .somedata}}</p> </body> 

and somefunc returns error. there idiomatic way deal this?

if write directly responsewriter, status code 200 has been written before encounter error.

var tmpl *template.template  func handler(w http.responsewriter, r *http.request) {     err := tmpl.execute(w, data)     // "<html><body><p>" has been written...     // err? } 

preferably return status code 400 or such, can't see way if use template.execute directly on responsewriter. there i'm missing?

since template engine generates output on-the-fly, parts of template preceding somefunc call sent output. , if output not buffered, (along http 200 status) may sent.

you can't that.

what can perform check before call template.execute(). in trivial case should enough call somefunc() , check return value. if choose path , return value of somefunc() complex, not have call again template, can pass return value params pass template , refer value in template (so somefunc() won't have executed twice).

if not enough or can't control it, can create bytes.buffer, execute template directed buffer, , after execute() returns, check if there errors. if there errors, send proper error message / page. if went ok, can send content of buffer responsewriter.

this this:

buf := &bytes.buffer{} err := tmpl.execute(buf, data) if err != nil {     // send error message, example:     http.error(w, "hey, request bad!", http.statusbadrequest) // http 400 status } else {     // no error, send content, http 200 response status implied     buf.writeto(w) } 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -