response.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. "github.com/miniflux/miniflux2/server/template"
  7. "net/http"
  8. "time"
  9. )
  10. type Response struct {
  11. writer http.ResponseWriter
  12. request *http.Request
  13. template *template.TemplateEngine
  14. }
  15. func (r *Response) SetCookie(cookie *http.Cookie) {
  16. http.SetCookie(r.writer, cookie)
  17. }
  18. func (r *Response) Json() *JsonResponse {
  19. r.commonHeaders()
  20. return &JsonResponse{writer: r.writer, request: r.request}
  21. }
  22. func (r *Response) Html() *HtmlResponse {
  23. r.commonHeaders()
  24. return &HtmlResponse{writer: r.writer, request: r.request, template: r.template}
  25. }
  26. func (r *Response) Xml() *XmlResponse {
  27. r.commonHeaders()
  28. return &XmlResponse{writer: r.writer, request: r.request}
  29. }
  30. func (r *Response) Redirect(path string) {
  31. http.Redirect(r.writer, r.request, path, http.StatusFound)
  32. }
  33. func (r *Response) Cache(mime_type, etag string, content []byte, duration time.Duration) {
  34. r.writer.Header().Set("Content-Type", mime_type)
  35. r.writer.Header().Set("Etag", etag)
  36. r.writer.Header().Set("Cache-Control", "public")
  37. r.writer.Header().Set("Expires", time.Now().Add(duration).Format(time.RFC1123))
  38. if etag == r.request.Header.Get("If-None-Match") {
  39. r.writer.WriteHeader(http.StatusNotModified)
  40. } else {
  41. r.writer.Write(content)
  42. }
  43. }
  44. func (r *Response) commonHeaders() {
  45. r.writer.Header().Set("X-XSS-Protection", "1; mode=block")
  46. r.writer.Header().Set("X-Content-Type-Options", "nosniff")
  47. r.writer.Header().Set("X-Frame-Options", "DENY")
  48. }
  49. func NewResponse(w http.ResponseWriter, r *http.Request, template *template.TemplateEngine) *Response {
  50. return &Response{writer: w, request: r, template: template}
  51. }