rusthyper

How can I return custom headers but no body? Using Hyper in Rust


What I want to do is return headers in hyper but without returning a body as such. My code currently is this:

use std::{convert::Infallible, net::SocketAddr};
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};

async fn handle(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    let body = "Hello, world!";

     let response = Response::builder()
        .header("Content-Type", "text/html")
        .header("Location, www.example.com")
        .header("content-length", body.len())
        .body(body.into())
        .unwrap();
}

#[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(handle))
    });

    let server = Server::bind(&addr).serve(make_svc);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}

As you can see, I return the Location header, so I expect the user to be redirected to www.example.com, but that doesn't happen. I guess that's because there's an html body that it returns, which returns as text Hello, world!, and that body prevents the redirect from going through. But, the function expects a response html body, so what can I do? How can I return the headers without a body in this function? Or is there something I'm misunderstanding?


Solution

  • To make the response perform a redirection, set the status code to one of the 3xx codes. The body should not be causing a problem, but to return a response without a body, use Body::empty(). It's also a good idea to use the constants from hyper for common status codes and header names.

         let response = Response::builder()
            .status(hyper::StatusCode::FOUND)
            .header(hyper::header::LOCATION, "https://www.example.com")
            .body(Body::empty())
            .unwrap();