html_response.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package core
  5. import (
  6. "net/http"
  7. "github.com/miniflux/miniflux/logger"
  8. "github.com/miniflux/miniflux/server/template"
  9. )
  10. // HTMLResponse handles HTML responses.
  11. type HTMLResponse struct {
  12. writer http.ResponseWriter
  13. request *http.Request
  14. template *template.Engine
  15. }
  16. // Render execute a template and send to the client the generated HTML.
  17. func (h *HTMLResponse) Render(template string, args map[string]interface{}) {
  18. h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
  19. h.template.Execute(h.writer, template, args)
  20. }
  21. // ServerError sends a 500 error to the browser.
  22. func (h *HTMLResponse) ServerError(err error) {
  23. h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
  24. h.writer.WriteHeader(http.StatusInternalServerError)
  25. if err != nil {
  26. logger.Error("[Internal Server Error] %v", err)
  27. h.writer.Write([]byte("Internal Server Error: " + err.Error()))
  28. } else {
  29. h.writer.Write([]byte("Internal Server Error"))
  30. }
  31. }
  32. // BadRequest sends a 400 error to the browser.
  33. func (h *HTMLResponse) BadRequest(err error) {
  34. h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
  35. h.writer.WriteHeader(http.StatusBadRequest)
  36. if err != nil {
  37. logger.Error("[Bad Request] %v", err)
  38. h.writer.Write([]byte("Bad Request: " + err.Error()))
  39. } else {
  40. h.writer.Write([]byte("Bad Request"))
  41. }
  42. }
  43. // NotFound sends a 404 error to the browser.
  44. func (h *HTMLResponse) NotFound() {
  45. h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
  46. h.writer.WriteHeader(http.StatusNotFound)
  47. h.writer.Write([]byte("Page Not Found"))
  48. }
  49. // Forbidden sends a 403 error to the browser.
  50. func (h *HTMLResponse) Forbidden() {
  51. h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
  52. h.writer.WriteHeader(http.StatusForbidden)
  53. h.writer.Write([]byte("Access Forbidden"))
  54. }