Implements a [Codec
] for encoding and decoding [Server-Sent Events] streams.
Advantages:
FramedWrite
] and [FramedRead
] while parsing linesAsyncRead
] or [AsyncWrite
]miette::Diagnostic
] for better error and diagnostic messages```rust use futures::StreamExt; use tokioutil::codec::{FramedRead, Decoder}; use tokiosse_codec::{SseDecoder, Frame, Event, SseDecodeError};
async fn main() -> Result<(), SseDecodeError> {
// you can use any stream or type that implements AsyncRead
let data = "id: 1\nevent: example\ndata: hello, world\n\n";
let mut reader = FramedRead::new(data.as_bytes(), SseDecoder::
while let Some(Ok(frame)) = reader.next().await {
match frame {
Frame::Event(event) => println!("event: id={:?}, name={}, data={}", event.id, event.name, event.data),
Frame::Comment(comment) => println!("comment: {}", comment),
Frame::Retry(duration) => println!("retry: {:#?}", duration),
}
}
Ok::<(), SseDecodeError>(())
} ```
By default, the decoder will not limit the size of the buffer used to store the data of an event. It's recommended to set one when dealing with untrusted input, otherwise a malicious server could send a very large event and consume all available memory.
The buffer should be able to hold a single event and it's data.
```rust use tokiossecodec::SseDecoder;
let decoder = SseDecoder::