networking · intermediate · ~15 min

Build an HTTP response

Emit a status line, Content-Length, and body.

Challenge

Assemble the bytes of a minimal HTTP/1.1 response: a status line, a Content-Length header, a blank line, and the body.

Task

Implement int build_response(char *out, int outsz, int code, const char *body) that writes this exact response into out and returns its length:

HTTP/1.1 <code> OK\r\nContent-Length: <len>\r\n\r\n<body>

where <len> is strlen(body).

Input

  • out, outsz: destination buffer and its size.
  • code: the numeric status code (e.g. 200).
  • body: the response body string.

Output

Returns the length of the response written (the snprintf return value).

Example

build_response(out, 256, 200, "hi")   ->   out="HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"

Edge cases

  • Content-Length must equal the body length exactly so the client knows where the body ends.

Rules

  • Use the literal reason phrase OK after the code, and CRLF (\r\n) line endings.

Input format

An output buffer (out) with size (outsz), a status code, and a body string.

Output format

The length of the written response.

Constraints

Format: 'HTTP/1.1 OK\r\nContent-Length: \r\n\r\n'. Use CRLF line endings.

Starter code

#include <stdio.h>
#include <string.h>

int build_response(char *out, int outsz, int code, const char *body) {
    /* TODO */
    return 0;
}

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