networking · intermediate · ~25 min

Final Project: HTTP status-line parser

Defensive text parsing of a structured one-liner.

Challenge

Pull the status code and reason phrase out of an HTTP response's first line — the first thing a health-checker or load balancer reads.

Task

Implement int http_parse_status(const char *line, int *out_code, char *out_reason, size_t cap).

The status line has the form HTTP/1.x CODE REASON (a trailing \r\n is optional), e.g. HTTP/1.1 200 OK\r\n. Set *out_code to the 3-digit code and copy the reason phrase (without CRLF) into out_reason.

Input

  • line: the NUL-terminated status line.
  • out_code: receives the 3-digit status code as an int.
  • out_reason, cap: output buffer for the reason phrase and its capacity (cap >= 1).

Output

Return 1 on success. Set *out_code to the integer code and copy the reason into out_reason, NUL-terminated and truncated to at most cap-1 bytes. Return 0 on malformed input (wrong version prefix, code not exactly 3 digits, missing spaces).

Example

"HTTP/1.1 200 OK\r\n"        ->  1, code=200, reason="OK"
"HTTP/1.0 404 Not Found"      ->  1, code=404, reason="Not Found"
"HTTP/1.1 500 \r\n"          ->  1, code=500, reason=""        (empty reason allowed)
"garbage"                     ->  0
"HTTP/2.0 abc OK"             ->  0   (code not 3 digits)

Edge cases

  • Both HTTP/1.0 and HTTP/1.1 are valid; the code must be exactly 3 ASCII digits.
  • An empty reason phrase is allowed.

Rules

  • No allocations; always NUL-terminate out_reason and never write past cap.

Why this matters

HTTP is just text on a socket. Parsing the status line is the first step in writing a checker, a load balancer, or a service-monitoring tool. Real production HTTP libraries have made this mistake — RFC 7230 ambiguity is a known foot-gun.

Input format

line, the NUL-terminated status line; out_code for the code; out_reason/cap for the reason phrase.

Output format

1 on success with *out_code set and out_reason filled (NUL-terminated, truncated to cap-1); 0 on malformed input.

Constraints

No allocations; cap >= 1; version must be HTTP/1.0 or 1.1; code exactly 3 digits.

Starter code

#include <stddef.h>
int http_parse_status(const char *line, int *out_code, char *out_reason, size_t cap) { /* TODO */ return 0; }

Common mistakes

Trusting sscanf (which won't handle the bounded reason copy); failing if there's no reason phrase (some servers emit none); confusing CR and LF.

Edge cases to handle

HTTP/1.0 or HTTP/1.1 both valid. Code must be 3 ASCII digits. Empty reason is allowed.

Complexity

O(line length).

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.