pub fn http_response(status: u16, content_type: &str, body: Vec<u8>) -> Vec<u8> ⓘExpand description
Constructs an HTTP response with the given status, content type, and body.
This is a utility function for creating properly formatted HTTP/1.1 responses. The response includes standard headers and follows HTTP protocol conventions.
§Arguments
status- HTTP status code (e.g., 200, 404, 500)content_type- MIME type of the response bodybody- The response body as bytes
§Returns
Returns a complete HTTP response as a byte vector, ready to be written to a socket.
§Response Format
HTTP/1.1 {status} {status_text}\r\n
Content-Type: {content_type}\r\n
Content-Length: {body_length}\r\n
Connection: close\r\n
\r\n
{body}§Status Codes
Common status codes:
200 OK: Successful request404 Not Found: File not found500 Internal Server Error: Server error
§Examples
§Success Response
use wsforge::static_files::http_response;
let html = b"<html><body>Hello!</body></html>".to_vec();
let response = http_response(200, "text/html", html);
// Response will be:
// HTTP/1.1 200 OK
// Content-Type: text/html
// Content-Length: 32
// Connection: close
//
// <html><body>Hello!</body></html>§404 Not Found
use wsforge::static_files::http_response;
let html = b"<html><body><h1>404 Not Found</h1></body></html>".to_vec();
let response = http_response(404, "text/html", html);§JSON Response
use wsforge::static_files::http_response;
let json = br#"{"error":"Not found"}"#.to_vec();
let response = http_response(404, "application/json", json);§Binary Response
use wsforge::static_files::http_response;
let image_data = vec![0x89, 0x50, 0x4E, 0x47]; // PNG header
let response = http_response(200, "image/png", image_data);§Server Error
use wsforge::static_files::http_response;
let error_html = b"<html><body><h1>500 Internal Server Error</h1></body></html>".to_vec();
let response = http_response(500, "text/html", error_html);