response.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2018 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 response
  5. import (
  6. "compress/flate"
  7. "compress/gzip"
  8. "net/http"
  9. "strings"
  10. "time"
  11. )
  12. // Redirect redirects the user to another location.
  13. func Redirect(w http.ResponseWriter, r *http.Request, path string) {
  14. http.Redirect(w, r, path, http.StatusFound)
  15. }
  16. // NotModified sends a response with a 304 status code.
  17. func NotModified(w http.ResponseWriter) {
  18. w.WriteHeader(http.StatusNotModified)
  19. }
  20. // Cache returns a response with caching headers.
  21. func Cache(w http.ResponseWriter, r *http.Request, mimeType, etag string, data []byte, duration time.Duration) {
  22. w.Header().Set("Content-Type", mimeType)
  23. w.Header().Set("ETag", etag)
  24. w.Header().Set("Cache-Control", "public")
  25. w.Header().Set("Expires", time.Now().Add(duration).Format(time.RFC1123))
  26. if etag == r.Header.Get("If-None-Match") {
  27. w.WriteHeader(http.StatusNotModified)
  28. return
  29. }
  30. switch mimeType {
  31. case "text/javascript; charset=utf-8", "text/css; charset=utf-8":
  32. Compress(w, r, data)
  33. default:
  34. w.Write(data)
  35. }
  36. }
  37. // Compress the response sent to the browser.
  38. func Compress(w http.ResponseWriter, r *http.Request, data []byte) {
  39. acceptEncoding := r.Header.Get("Accept-Encoding")
  40. switch {
  41. case strings.Contains(acceptEncoding, "gzip"):
  42. w.Header().Set("Content-Encoding", "gzip")
  43. gzipWriter := gzip.NewWriter(w)
  44. defer gzipWriter.Close()
  45. gzipWriter.Write(data)
  46. case strings.Contains(acceptEncoding, "deflate"):
  47. w.Header().Set("Content-Encoding", "deflate")
  48. flateWriter, _ := flate.NewWriter(w, -1)
  49. defer flateWriter.Close()
  50. flateWriter.Write(data)
  51. default:
  52. w.Write(data)
  53. }
  54. }