Skip to content

How to trim in Rust #2642

@sm8082

Description

@sm8082

Hi,
I wonder how I can trim the spaces before counting the string length before sending the result of my response in PostMan platform. The response is displayed in PostMan. I'm referring to the code line "let count_it = body.iter().count().to_string();". This is where its counting the length of string. Could you please assist me so that "count_it" variable contains the length of string without counting any spaces in between or on the start and end of it. Thanks:

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) -> Result<Response, 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"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions