summaryrefslogtreecommitdiffhomepage
path: root/response.c
blob: df465d0c92801d0c1ad53fcc14eb431cd6353d99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "response.h"

#include <stdio.h>
#include <unistd.h>

#include "http.h"

/// Sends a simple response only with a status to the client.
/// \param fd File descriptor of the client socket
/// \param status HTTP response status code
/// \return Negative value if an error was encountered; numbers of bytes written otherwise
int respond_only_status(const int fd, const enum status status)
{
	static const char * pattern =
		"HTTP/1.1 %s\r\n"
		"Connection: close\r\n"
		"\r\n";

	return dprintf(fd, pattern, status_str[status]);
}

/// Sends a response with a status and a body to the client.
/// \param fd File descriptor of the client socket
/// \param status HTTP response status code
/// \param body Content that will be sent
/// \param size Size of the content in bytes
/// \return Negative value if an error was encountered; numbers of bytes written otherwise
int respond_with_body(const int fd, const enum status status, const char * body, const int size)
{
	static const char * pattern =
		"HTTP/1.1 %s\r\n"
		"Connection: close\r\n"
		"Content-Type: application/json\r\n"
		"Content-Size: %d\r\n"
		"\r\n";

	if (0 > dprintf(fd, pattern, status_str[status], size))
	{
		return -1; // TODO: Handle errors properly
	}

	return write(fd, body, size);
}