Add caching to static files based on etag
This commit is contained in:
parent
f2e52a18e5
commit
06495fa358
2 changed files with 16 additions and 19 deletions
|
|
@ -2,7 +2,6 @@ package middleware
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"hash/crc64"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
|
@ -13,11 +12,8 @@ type ETag struct {
|
|||
Name string
|
||||
Value string
|
||||
Expiration time.Duration
|
||||
HashTime time.Duration
|
||||
}
|
||||
|
||||
var etags = make([]*ETag, 0)
|
||||
|
||||
func (etag *ETag) Header() string {
|
||||
return fmt.Sprintf("\"pb-%s-%s\"", etag.Name, etag.Value)
|
||||
}
|
||||
|
|
@ -46,21 +42,10 @@ func StaticEtagMiddleware(etag ETag, next http.Handler) http.Handler {
|
|||
}
|
||||
|
||||
// GenerateETagFromBuffer calculates etag value from one or more buffers (e.g. embedded files)
|
||||
func GenerateETagFromBuffer(name string, expiration time.Duration, buffers ...[]byte) (*ETag, error) {
|
||||
start := time.Now()
|
||||
hash := crc64.New(crc64.MakeTable(crc64.ECMA))
|
||||
for _, buffer := range buffers {
|
||||
_, err := hash.Write(buffer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to generate etag from buffer: %w", err)
|
||||
}
|
||||
}
|
||||
etag := &ETag{
|
||||
func NewETag(name string, expiration time.Duration) *ETag {
|
||||
return &ETag{
|
||||
Name: name,
|
||||
Expiration: expiration,
|
||||
Value: fmt.Sprintf("%x", hash.Sum64()),
|
||||
HashTime: time.Since(start),
|
||||
Value: fmt.Sprintf("%d", time.Now().Unix()),
|
||||
}
|
||||
etags = append(etags, etag)
|
||||
return etag, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue