Cache Encodings with the Go Client

Tip
The source code for this tutorial is available on GitHub.

This tutorial demonstrates how to use different cache encodings with the Go Hot Rod client.

Prerequisites

  • A running Infinispan server.

  • Go 1.25 or later.

Running the Example

go run ./encoding

Code Walkthrough

Text Cache

Create a cache with text/plain encoding by calling WithEncoding on the cache reference.

textCache := client.Cache("textCache").WithEncoding(hotrod.MediaTypeTextPlain)
textCache.Put(ctx, []byte("greeting"), []byte("Hello, Infinispan!"))
val, found, err := textCache.Get(ctx, []byte("greeting"))

JSON Cache

Create a cache with application/json encoding and store JSON documents.

jsonCache := client.Cache("jsonCache").WithEncoding(hotrod.MediaTypeJSON)
jsonCache.Put(ctx, []byte(`"name"`), []byte(`{"project": "infinispan"}`))

Separate Key and Value Encodings

When keys and values use different media types, use WithKeyEncoding and WithValueEncoding:

cache := client.Cache("mixed").
    WithKeyEncoding(hotrod.MediaTypeTextPlain).
    WithValueEncoding(hotrod.MediaTypeJSON)

Expected Output

Caches ready.

== Cache with text/plain encoding ==
textCache[greeting] = Hello, Infinispan!

== Cache with application/json encoding ==
jsonCache[name] = {"project": "infinispan"}

Caches removed.