package imagerequest import ( "crypto/sha256" "encoding/hex" "fmt" "strings" ) // VariantKey is a SHA256 hash identifying a specific image variant (hex-encoded). type VariantKey string // CacheKey generates a unique key for a request variant. // Format: sha256(host:path:query:width:height:format:quality:fit_mode) // The path and query go through escapePercentAndColon, so that a ":" in // either cannot be taken for the one between them. func CacheKey(req *Request) VariantKey { data := fmt.Sprintf("%s:%s:%s:%d:%d:%s:%d:%s", req.Source.Host, escapePercentAndColon(req.Source.Path), escapePercentAndColon(req.Source.Query), req.Transform.Size.Width, req.Transform.Size.Height, req.Transform.Format, req.Transform.Quality, req.Transform.FitMode, ) h := sha256.Sum256([]byte(data)) return VariantKey(hex.EncodeToString(h[:])) } // escapePercentAndColon returns s with each "%" written as "%25" and each // ":" as "%3A", so that the result holds no ":". func escapePercentAndColon(s string) string { s = strings.ReplaceAll(s, "%", "%25") return strings.ReplaceAll(s, ":", "%3A") }