Encode encodes the given value to a string.
(ctx context.Context, cipher aead.Cipher, val any, opts ...CodecOption)
| 95 | |
| 96 | // Encode encodes the given value to a string. |
| 97 | func Encode(ctx context.Context, cipher aead.Cipher, val any, opts ...CodecOption) (s string, err error) { |
| 98 | // Steps: |
| 99 | // 1. Encode to JSON |
| 100 | // 2. GZIP |
| 101 | // 3. Encrypt with AEAD (XChaCha20-Poly1305) + Base64 URL-encode |
| 102 | var b bytes.Buffer |
| 103 | |
| 104 | gz, err := gzip.NewWriterLevel(&b, gzip.BestCompression) |
| 105 | if err != nil { |
| 106 | return "", err |
| 107 | } |
| 108 | |
| 109 | if err = json.NewEncoder(gz).Encode(val); err != nil { |
| 110 | return "", err |
| 111 | } |
| 112 | |
| 113 | if err = gz.Close(); err != nil { |
| 114 | return "", err |
| 115 | } |
| 116 | |
| 117 | return cipher.Encrypt(ctx, b.Bytes(), additionalDataFromOpts(opts...)) |
| 118 | } |