etag.go 881 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package main
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "hash"
  8. "sync"
  9. "github.com/imgproxy/imgproxy/v2/imagedata"
  10. "github.com/imgproxy/imgproxy/v2/options"
  11. "github.com/imgproxy/imgproxy/v2/version"
  12. )
  13. type eTagCalc struct {
  14. hash hash.Hash
  15. enc *json.Encoder
  16. }
  17. var eTagCalcPool = sync.Pool{
  18. New: func() interface{} {
  19. h := sha256.New()
  20. enc := json.NewEncoder(h)
  21. enc.SetEscapeHTML(false)
  22. enc.SetIndent("", "")
  23. return &eTagCalc{h, enc}
  24. },
  25. }
  26. func calcETag(ctx context.Context, imgdata *imagedata.ImageData, po *options.ProcessingOptions) string {
  27. c := eTagCalcPool.Get().(*eTagCalc)
  28. defer eTagCalcPool.Put(c)
  29. c.hash.Reset()
  30. c.hash.Write(imgdata.Data)
  31. footprint := c.hash.Sum(nil)
  32. c.hash.Reset()
  33. c.hash.Write(footprint)
  34. c.hash.Write([]byte(version.Version()))
  35. c.enc.Encode(po)
  36. return hex.EncodeToString(c.hash.Sum(nil))
  37. }