Files
schreifuchs.ch/internal/components/images/helpers.go
T
2026-03-02 22:38:29 +01:00

69 lines
1.4 KiB
Go

package images
import (
"bytes"
"compress/flate"
"encoding/base64"
"fmt"
"io"
"strings"
)
func UIDFromPath(path string) (uid string, err error) {
var b bytes.Buffer
// NewWriter with NoDict (nil) creates a raw DEFLATE compressor
zw, _ := flate.NewWriter(&b, flate.BestCompression)
_, err = zw.Write([]byte(path))
if err != nil {
return
}
err = zw.Close() // Essential to flush the final bits
if err != nil {
return
}
return base64.RawURLEncoding.EncodeToString(b.Bytes()), nil
}
func URLFromPath(path string) (url string, err error) {
uid, err := UIDFromPath(path)
url = "/images/" + uid
return
}
func PathFromUID(uid string) (string, error) {
// 1. Decode the Base64 string back to compressed bytes
compressedBytes, err := base64.RawURLEncoding.DecodeString(uid)
if err != nil {
return "", err
}
// 2. Create a flate reader (NoDict/nil since you used nil in the writer)
// flate.NewReader returns an io.ReadCloser
reader := flate.NewReader(bytes.NewReader(compressedBytes))
defer reader.Close()
// 3. Read the decompressed data into a buffer
var out bytes.Buffer
_, err = io.Copy(&out, reader)
if err != nil {
return "", err
}
return out.String(), nil
}
func SourceSet(src string) string {
sb := strings.Builder{}
for i := range 19 {
sb.WriteString(fmt.Sprintf("%s?w=%d %dw, ", src, 100*(i+1), 100*(i+1)))
}
i := 20
sb.WriteString(fmt.Sprintf("%s?w=%d %dw", src, 100*(i+1), 100*(i+1)))
return sb.String()
}