liveBook · Manning

Http request parsing

As explained in Rust Servers, Services, and Apps

HTTP request parsing is the process of interpreting an HTTP request representation and extracting its method, path, version, headers, and body.

HTTP request parsing turns an incoming request string into an HttpRequest value containing a method, resource path, version, headers, and message body. A Rust server models these parts with enums, a struct, and a HashMap. section 2.3.1

A compact implementation builds the parser in layers:

  • Convert GET and POST strings into Method variants, defaulting unknown methods to Uninitialized. section 2.3.1
  • Convert HTTP/1.1 into Version::V1_1 and retain an Uninitialized variant for unsupported versions. section 2.3.1
  • Split the request line on whitespace to extract method, resource path, and version; split header lines at the colon separator. section 2.3.1
  • Implement From<String> for HttpRequest so the parser can convert a complete request into the server’s data structure. section 2.3.1

Testing a parsed request

Feed the parser a GET /greeting HTTP/1.1 request with Host, User-Agent, and Accept headers, then assert the method, version, and resource path. Run cargo test -p http and verify all three tests pass. section 2.3.1

Table 2.1 The data structures for incoming HTTP requests (view table figure)

Data structure name

Rust data type

Description

HttpRequest

struct

Represents an HTTP request

Method

enum

Specifies the allowed values (variants) for HTTP methods

Version

enum

Specifies the allowed values for HTTP Versions

Browse the request data structures and their roles before following the parsing implementation. section 2.3.1

How Rust Servers, Services, and Apps covers it

How deep it goes
Explains data structures, conversions, line parsing, assembly, and unit tests, but does not develop production-grade validation.
Examples
Uses GET and POST conversions plus a GET /greeting request containing Host, User-Agent, and Accept headers.
What it assumes
Assumes basic Rust familiarity while defining the required request structures, conversions, and tests in context.
What you can do after
Builds a Rust parser that converts incoming HTTP request strings into HttpRequest structures and tests its extracted fields.
How it connects
Connects HTTP methods, HTTP versions, resource paths, headers, request bodies, Rust traits, and unit testing.

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