clientSideDigestExample demonstrates calculating digests without fetching from Redis
(ctx context.Context, rdb *redis.Client)
| 198 | |
| 199 | // clientSideDigestExample demonstrates calculating digests without fetching from Redis |
| 200 | func clientSideDigestExample(ctx context.Context, rdb *redis.Client) { |
| 201 | key := "product:1001:price" |
| 202 | |
| 203 | // Scenario: We know the expected current value |
| 204 | expectedCurrentValue := "29.99" |
| 205 | newValue := "24.99" |
| 206 | |
| 207 | // Set initial value |
| 208 | rdb.Set(ctx, key, expectedCurrentValue, 0) |
| 209 | fmt.Printf("Current price: $%s\n", expectedCurrentValue) |
| 210 | |
| 211 | // Calculate digest client-side (no need to fetch from Redis!) |
| 212 | expectedDigest := helper.DigestString(expectedCurrentValue) |
| 213 | fmt.Printf("Expected digest (calculated client-side): 0x%016x\n", expectedDigest) |
| 214 | |
| 215 | // Update price only if it matches our expectation |
| 216 | result := rdb.SetIFDEQ(ctx, key, newValue, expectedDigest, 0) |
| 217 | |
| 218 | if result.Err() == redis.Nil { |
| 219 | fmt.Println("✗ Price was already changed by someone else") |
| 220 | actualValue := rdb.Get(ctx, key).Val() |
| 221 | fmt.Printf(" Actual current price: $%s\n", actualValue) |
| 222 | } else if result.Err() != nil { |
| 223 | fmt.Printf("✗ Error: %v\n", result.Err()) |
| 224 | } else { |
| 225 | fmt.Printf("✓ Price updated successfully to $%s\n", newValue) |
| 226 | } |
| 227 | |
| 228 | // Demonstrate with binary data |
| 229 | fmt.Println("\nBinary data example:") |
| 230 | binaryKey := "image:thumbnail" |
| 231 | binaryData := []byte{0xFF, 0xD8, 0xFF, 0xE0} // JPEG header |
| 232 | |
| 233 | rdb.Set(ctx, binaryKey, binaryData, 0) |
| 234 | |
| 235 | // Calculate digest for binary data |
| 236 | binaryDigest := helper.DigestBytes(binaryData) |
| 237 | fmt.Printf("Binary data digest: 0x%016x\n", binaryDigest) |
| 238 | |
| 239 | // Verify it matches Redis |
| 240 | redisDigest := rdb.Digest(ctx, binaryKey).Val() |
| 241 | if binaryDigest == redisDigest { |
| 242 | fmt.Println("✓ Binary digest matches!") |
| 243 | } |
| 244 | } |
no test coverage detected