How to trim in Rust #2644
-
Hi, Main.rs code as below: //#![deny(warnings)]
use std::{convert::Infallible, net::SocketAddr};
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Method, StatusCode};
#[tokio::main]
async fn main() {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(run))
});
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}
async fn run(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
let mut response = Response::new(Body::empty());
match (req.method(), req.uri().path()) {
(&Method::POST, "/echo/count/chars") => {
let body = hyper::body::to_bytes(req.into_body()).await?;
let count_it = body.iter().count().to_string();
*response.body_mut() = count_it.into();
},
_ => {
*response.status_mut() = StatusCode::NOT_FOUND;
},
};
Ok(response)
} Cargo.toml: [dependencies]
hyper = { version = "0.14", features = ["full"] }
tokio = { version = "1", features = ["full"] }
futures = "0.3.16" |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You could parse the bytes as a string with match std::str::from_utf8(&body) {
Ok(text) => {
let count_it = text.trim().len().to_string();
*response.body_mut() = count_it.into();
},
Err(_not_utf8) => {
*response.status_mut() = StatusCode::BAD_REQUEST;
*response.body_mut() = "Not UTF-8".into();
}
} |
Beta Was this translation helpful? Give feedback.
You could parse the bytes as a string with
from_utf8
, and then usestr.trim()
: