liveBook · Manning

Content-Length header

As explained in Refactoring to Rust

The Content-Length header is an HTTP header that declares the size in bytes of a response body.

The Content-Length header declares a response body's size in bytes. When a response body is provided without chunked encoding, set the status and length before sending the headers. section 4.6

let headers = &mut request.headers_out;  #1

  headers.status = status_code;

  let response_bytes = response_body.as_bytes();  #2
  headers.content_length_n = response_bytes.len() as off_t;  #3

  let rc = ngx_http_send_header(request);
  if rc != 0 {
    return Err("failed to send headers");
  }

Convert the response string to bytes, count them with len(), cast the count to NGINX's offset type, and send the headers. section 4.6

Setting the response length

For response_body, obtain response_body.as_bytes(), assign response_bytes.len() as off_t to headers.content_length_n, then call ngx_http_send_header(request). section 4.6

How Refactoring to Rust covers it

How deep it goes
Explains the no-chunked-body requirement and demonstrates byte conversion, length calculation, type casting, and header transmission.
Examples
Uses response_body.as_bytes(), response_bytes.len() as off_t, headers.content_length_n, and ngx_http_send_header.
What you can do after
Operate NGINX response handling by declaring body length before passing headers and body data to output handlers.
How it connects
Connects HTTP response headers with response bodies, chunked encoding, NGINX, and unsafe Rust FFI.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.