Commit bdd145b0 authored by Matthew Holt's avatar Matthew Holt

Better error handling when executing templates

parent 0cbaed24
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
package browse package browse
import ( import (
"bytes"
"fmt" "fmt"
"html/template" "html/template"
"io/ioutil" "io/ioutil"
...@@ -122,8 +123,6 @@ func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { ...@@ -122,8 +123,6 @@ func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
} }
defer file.Close() defer file.Close()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
files, err := file.Readdir(-1) files, err := file.Readdir(-1)
if err != nil { if err != nil {
return http.StatusForbidden, err return http.StatusForbidden, err
...@@ -182,11 +181,14 @@ func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { ...@@ -182,11 +181,14 @@ func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
Items: fileinfos, Items: fileinfos,
} }
// TODO: Don't write to w until we know there wasn't an error // TODO: Use pooled buffers to reduce allocations
err = bc.Template.Execute(w, listing) var buf bytes.Buffer
err = bc.Template.Execute(&buf, listing)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
w.Header().Set("Content-Type", "text/html; charset=utf-8")
buf.WriteTo(w)
return http.StatusOK, nil return http.StatusOK, nil
} }
......
package templates package templates
import ( import (
"bytes"
"net/http" "net/http"
"path" "path"
"text/template" "text/template"
...@@ -47,10 +48,13 @@ func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error ...@@ -47,10 +48,13 @@ func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error
} }
// Execute it // Execute it
err = tpl.Execute(w, ctx) // TODO: Use pooled buffers to reduce allocations
var buf bytes.Buffer
err = bc.Template.Execute(&buf, ctx)
if err != nil { if err != nil {
return http.StatusInternalServerError, err return http.StatusInternalServerError, err
} }
buf.WriteTo(w)
return http.StatusOK, nil return http.StatusOK, nil
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment