Search code examples
rustactix-web

How to return a NamedFile in a HttpResponse using Actix-web


I try to return a NamedFile in a HttpRespose with this function

fn response(x: NamedFile)->HttpResponse{
        HttpResponse::Ok()
        .content_type(ContentType::html())
        .insert_header(("X-Hdr", "sample"))
        .body(x)
}

The function get called in my index file and returns the HttpRequest
is this even possible???


Solution

  • i solved it by introducing a new function that converts the content of the file into a single string

    fn open(x: PathBuf) -> String{
        return fs::read_to_string(x)
            .expect("Something went wrong");
    }
    

    and used instead of NamedFile a String the function looks like this:

    fn response(x: String, y:Response)->HttpResponse{
    
        match y{
            Response::OK => {
            HttpResponse::Ok()
            .content_type(ContentType::html())
            .insert_header(("X-Hdr", "sample"))
            .body(x)
            }
            Response::NOTOK => {
                HttpResponse::NotFound()
            .content_type(ContentType::html())
            .insert_header(("X-Hdr", "sample"))
            .body(x)
            }   
        }   
    }