networking · intermediate · ~15 min

Parse the request line

Split an HTTP request line into fields.

Challenge

An HTTP request line has three space-separated tokens: METHOD SP PATH SP VERSION (e.g. GET /index.html HTTP/1.1). Extract the method and the path.

Task

Implement int parse_request_line(const char *line, char *method, int msz, char *path, int psz) that copies the first token into method and the second token into path.

Input

  • line: the request line.
  • method, msz: buffer and size for the method.
  • path, psz: buffer and size for the path.

Output

Returns 1 on success (method and path written), or 0 if line does not contain two spaces.

Example

parse_request_line("GET /index.html HTTP/1.1", ...)   ->   1, method="GET", path="/index.html"
parse_request_line("GET", ...)                        ->   0

Edge cases

  • Fewer than two spaces: return 0.
  • Copy each token bounded by its buffer size and NUL-terminate.

Input format

The request line (line), a method buffer (method, msz), and a path buffer (path, psz).

Output format

Returns 1 with method and path written, or 0 if there are not two spaces.

Constraints

Method is text before the 1st space; path is between the 1st and 2nd spaces. Bound copies and NUL-terminate.

Starter code

#include <string.h>

int parse_request_line(const char *line, char *method, int msz, char *path, int psz) {
    /* TODO */
    return 0;
}

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