notmodified.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package notmodified
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/imgproxy/imgproxy/v3/config"
  6. )
  7. func Response(req *http.Request, header http.Header) *http.Response {
  8. if config.ETagEnabled {
  9. etag := header.Get("ETag")
  10. ifNoneMatch := req.Header.Get("If-None-Match")
  11. if len(ifNoneMatch) > 0 && ifNoneMatch == etag {
  12. return response(req, header)
  13. }
  14. }
  15. if config.LastModifiedEnabled {
  16. lastModifiedRaw := header.Get("Last-Modified")
  17. if len(lastModifiedRaw) == 0 {
  18. return nil
  19. }
  20. ifModifiedSinceRaw := req.Header.Get("If-Modified-Since")
  21. if len(ifModifiedSinceRaw) == 0 {
  22. return nil
  23. }
  24. lastModified, err := time.Parse(http.TimeFormat, lastModifiedRaw)
  25. if err != nil {
  26. return nil
  27. }
  28. ifModifiedSince, err := time.Parse(http.TimeFormat, ifModifiedSinceRaw)
  29. if err != nil {
  30. return nil
  31. }
  32. if !ifModifiedSince.Before(lastModified) {
  33. return response(req, header)
  34. }
  35. }
  36. return nil
  37. }
  38. func response(req *http.Request, header http.Header) *http.Response {
  39. return &http.Response{
  40. StatusCode: http.StatusNotModified,
  41. Proto: "HTTP/1.0",
  42. ProtoMajor: 1,
  43. ProtoMinor: 0,
  44. Header: header,
  45. ContentLength: 0,
  46. Body: nil,
  47. Close: false,
  48. Request: req,
  49. }
  50. }