networking · intermediate · ~15 min

Parse the request method

Read the method off the request line.

Challenge

The first token of an HTTP request line is the method (GET, POST, ...). Extract it.

Task

Implement int request_method(const char *req, char *out, int outsz) that copies the method — everything up to the first space — into out (bounded by outsz) and returns its length.

Input

  • req: the request line (e.g. "GET /x HTTP/1.1").
  • out, outsz: destination buffer for the method and its size.

Output

Returns the method length on success, or -1 if req contains no space.

Example

request_method("GET /x HTTP/1.1", out, 16)   ->   3, out="GET"
request_method("GET", out, 16)               ->   -1   (no space)

Edge cases

  • No space anywhere: return -1.
  • Copy bounded by outsz and NUL-terminate.

Input format

The request line (req) and an output buffer (out) with size (outsz).

Output format

The method length on success, or -1 if there is no space.

Constraints

Method is the first token up to the first space. Copy bounded by outsz and NUL-terminate; return -1 if no space.

Starter code

#include <string.h>

int request_method(const char *req, char *out, int outsz) {
    /* TODO */
    return -1;
}

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