handler.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*
  2. Package render implements template inheritance and exposes functions to render HTML.
  3. inspired by http://elithrar.github.io/article/approximating-html-template-inheritance and https://github.com/sourcegraph/thesrc/blob/master/app/handler.go
  4. It also exports two types Binary and HMTL.
  5. Both wrap a http.HandlerFunc-like function with an error return value and argument the response.
  6. */
  7. package render
  8. import (
  9. "fmt"
  10. "log"
  11. "net/http"
  12. )
  13. // Binary sets Content-Description and Content-Transfer-Encoding
  14. // if h returns an error it returns http status 500
  15. type Binary func(resp http.ResponseWriter, req *http.Request) error
  16. func (h Binary) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
  17. resp.Header().Set("Content-Description", "File Transfer")
  18. resp.Header().Set("Content-Transfer-Encoding", "binary")
  19. if err := h(resp, req); err != nil {
  20. err = fmt.Errorf("render/binary: handler error serving %s: %w", req.URL, err)
  21. // TOODO: request injection
  22. log.Println("Binary/ServeHTTP:", err)
  23. http.Error(resp, err.Error(), http.StatusInternalServerError)
  24. }
  25. }
  26. // PlainError helps rendering user errors
  27. func PlainError(w http.ResponseWriter, r *http.Request, statusCode int, err error) {
  28. log.Println("PlainError:", err)
  29. // TOODO: request injection
  30. // xlog.FromContext(r.Context()).Error("PlainError", xlog.F{
  31. // "status": statusCode,
  32. // "err": errgo.Details(err),
  33. // })
  34. http.Error(w, err.Error(), statusCode)
  35. }