1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-08 10:45:04 +02:00
imgproxy/etag.go

94 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
2019-02-25 14:26:51 +02:00
"bytes"
2018-10-05 18:20:29 +02:00
"context"
"crypto/sha256"
2018-10-05 21:45:14 +02:00
"encoding/hex"
"encoding/json"
"hash"
"sync"
)
2019-02-25 14:26:51 +02:00
type etagPool struct {
mutex sync.Mutex
top *etagPoolEntry
}
type etagPoolEntry struct {
2018-10-05 21:45:14 +02:00
hash hash.Hash
enc *json.Encoder
2019-02-25 14:26:51 +02:00
buf *bytes.Buffer
next *etagPoolEntry
}
func newEtagPool(n int) *etagPool {
pool := new(etagPool)
for i := 0; i < n; i++ {
pool.grow()
}
return pool
}
func (p *etagPool) grow() {
h := sha256.New()
enc := json.NewEncoder(h)
enc.SetEscapeHTML(false)
enc.SetIndent("", "")
p.top = &etagPoolEntry{
hash: h,
enc: enc,
buf: new(bytes.Buffer),
next: p.top,
}
2018-10-05 21:45:14 +02:00
}
2019-02-25 14:26:51 +02:00
func (p *etagPool) Get() *etagPoolEntry {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.top == nil {
p.grow()
}
entry := p.top
p.top = p.top.next
2018-10-05 21:45:14 +02:00
2019-02-25 14:26:51 +02:00
return entry
}
func (p *etagPool) Put(e *etagPoolEntry) {
p.mutex.Lock()
defer p.mutex.Unlock()
2018-10-05 21:45:14 +02:00
2019-02-25 14:26:51 +02:00
e.next = p.top
p.top = e
2018-10-05 21:45:14 +02:00
}
2019-02-25 14:26:51 +02:00
var eTagCalcPool *etagPool
func calcETag(ctx context.Context) ([]byte, context.CancelFunc) {
c := eTagCalcPool.Get()
cancel := func() { eTagCalcPool.Put(c) }
2018-10-05 21:45:14 +02:00
c.hash.Reset()
c.hash.Write(getImageData(ctx).Bytes())
footprint := c.hash.Sum(nil)
c.hash.Reset()
c.hash.Write(footprint)
c.hash.Write([]byte(version))
c.enc.Encode(conf)
c.enc.Encode(getProcessingOptions(ctx))
2019-02-25 14:26:51 +02:00
c.buf.Reset()
enc := hex.NewEncoder(c.buf)
enc.Write(c.hash.Sum(nil))
return c.buf.Bytes(), cancel
}