Ниже показан английский оригинал.
JSON
JsonCodec reads and writes JSON through serde_json; it is the default codec, on with the json feature.
The json feature is a default feature of the crate.
While it is on, DefaultCodec is JsonCodec, so a handler mounted with no codec named decodes JSON, and a reply is encoded in JSON.
A message type derives serde::Deserialize; a type the handler publishes derives Serialize as well.
The media type is application/json, and the generated AsyncAPI document reports it for each message.
A payload that is not JSON, or JSON of another shape, is a decode failure, settled by the subscriber's failure policy.
To name JSON where another codec is the scope's, mount through a router or a registration that names it, as on Codecs.
Example
The example builds with JSON as the only codec:
cargo test --example codec_json --no-default-features --features testing,macros,memory,json
- Macros
- Manual
#[subscriber("orders")]
async fn bill(order: &Order) -> HandlerOutcome {
tracing::info!(order.id, "billed");
HandlerOutcome::ack()
}
fn app() -> impl App {
// No codec named anywhere: the handler decodes with the default codec, JSON.
RustStream::new(AppInfo::new("billing", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
b.include(bill);
})
}
struct Bill;
impl Handle<Order> for Bill {
fn handle(
&self,
order: &Order,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
tracing::info!(order.id, "billed");
ready(Ok(()))
}
}
fn app() -> impl App {
// No codec named anywhere: the registration decodes with the default codec, JSON.
RustStream::new(AppInfo::new("billing", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
b.include(subscriber("orders", Bill).build());
})
}