# Crafting Responses
While returning simple strings or JSON objects is often enough, there are times when you need precise control over the HTTP response—setting headers, cookies, or streaming large bodies. The HttpResponseBuilder is your tool for this.
##HttpResponse Builder
The HttpResponse struct has associated methods corresponding to HTTP status codes, which return an HttpResponseBuilder.
use actix_web::{HttpResponse, Responder};
async fn custom_headers() -> impl Responder {
HttpResponse::Ok()
.insert_header(("X-RateLimit-Remaining", "42"))
.content_type("text/plain")
.body("Header set!")
}##Cookies
Actix Web provides a Cookie struct in the actix_web::cookie module to handle cookies easily.
use actix_web::{cookie::Cookie, HttpResponse, Responder};
async fn set_cookie() -> impl Responder {
let cookie = Cookie::build("session_id", "xyz123")
.path("/")
.secure(true)
.http_only(true)
.finish();
HttpResponse::Ok()
.cookie(cookie)
.body("Cookie set")
}##Streaming Responses
If you need to send a very large file or a stream of data generated on the fly, you shouldn't load the entire payload into memory. Instead, you can return a Stream.
use actix_web::{HttpResponse, Responder};
use futures::stream::once;
use bytes::Bytes;
use std::future::ready;
async fn stream_body() -> impl Responder {
// Creating a very basic stream of a single chunk for demonstration
let chunk = Bytes::from_static(b"Hello from stream!");
let stream = once(ready(Ok::<_, actix_web::Error>(chunk)));
HttpResponse::Ok()
.content_type("application/octet-stream")
.streaming(stream)
}Actix Web is capable of incredibly fast streaming thanks to its non-blocking architecture, making it an excellent choice for video streaming or large file distribution.