[−][src]Module roa::body
This module provides a context extension PowerBody
.
Read/write body in a easier way.
The roa_core
provides several methods to read/write body.
use roa::{Context, Result}; use futures::AsyncReadExt; use futures::io::BufReader; use async_std::fs::File; async fn get(mut ctx: Context<()>) -> Result { let mut data = String::new(); // implements futures::AsyncRead. ctx.req.reader().read_to_string(&mut data).await?; println!("data: {}", data); // although body is empty now... let stream = ctx.req.stream(); ctx.resp // echo .write_stream(stream) // write object implementing futures::AsyncRead .write_reader(File::open("assets/author.txt").await?) // write reader with specific chunk size .write_chunk(File::open("assets/author.txt").await?, 1024) // write text .write("I am Roa.") .write(b"I am Roa.".as_ref()); Ok(()) }
These methods are useful, but they do not deal with headers and (de)serialization.
The PowerBody
provides more powerful methods to handle it.
use roa::{Context, Result}; use roa::body::{PowerBody, DispositionType::*}; use serde::{Serialize, Deserialize}; use askama::Template; use async_std::fs::File; use futures::io::BufReader; #[derive(Debug, Serialize, Deserialize, Template)] #[template(path = "user.html")] struct User { id: u64, name: String, } async fn get(mut ctx: Context<()>) -> Result { // read as bytes. let data = ctx.read().await?; // deserialize as json. let user: User = ctx.read_json().await?; // deserialize as x-form-urlencoded. let user: User = ctx.read_form().await?; // serialize object and write it to body, // set "Content-Type" ctx.write_json(&user)?; // open file and write it to body, // set "Content-Type" and "Content-Disposition" ctx.write_file("assets/welcome.html", Inline).await?; // write text, // set "Content-Type" ctx.write("Hello, World!"); // write object implementing AsyncRead, // set "Content-Type" ctx.write_reader(File::open("assets/author.txt").await?); // render html template, based on [askama](https://github.com/djc/askama). // set "Content-Type" ctx.render(&user)?; Ok(()) }
Enums
DispositionType | Type of content-disposition, inline or attachment |
Traits
PowerBody | A context extension to read/write body more simply. |