notmodified.go 1.2 KB

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