Add build_basic_request_method
parent
19449b3f1e
commit
5824b8f536
|
@ -0,0 +1,42 @@
|
|||
#include "http_socket.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/**
|
||||
* Gets the buffer size to allocate based on the given components.
|
||||
*
|
||||
* @param components An array of null-terminated C strings to measure the length of
|
||||
* @param num_components The number of items in the components array.
|
||||
*
|
||||
* @return The buffer size to allocate, excluding the null terminator
|
||||
*/
|
||||
static size_t get_buffer_size(const char **components, int num_components) {
|
||||
size_t buffer_size = 0;
|
||||
for (int i = 0; i < num_components; i++) {
|
||||
buffer_size += strlen(components[i]);
|
||||
}
|
||||
|
||||
return buffer_size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a basic request into an http_message
|
||||
*
|
||||
* @param method The HTTP method to use
|
||||
* @param host The host requested
|
||||
* @param path The path on the host requested
|
||||
* @param port The port of the host requested
|
||||
*
|
||||
* @return A http_message - note that the contents field has been mallocced and must be manually freed.
|
||||
*/
|
||||
struct http_message build_basic_request(const char *method, const char *host, const char *path, const char *port) {
|
||||
const char *request_line_components[] = {method, " ", path, " ", HTTP_VERSION, "\r\n"};
|
||||
const char *host_header[] = {"Host: ", host, "\r\n"};
|
||||
int message_buffer_size = get_buffer_size(request_line_components, 6) + get_buffer_size(host_header, 3) + 1;
|
||||
char *message_buffer = malloc(message_buffer_size * sizeof(char));
|
||||
sprintf(message_buffer, "%s %s %s\r\nHost: %s\r\n\r\n", method, path, HTTP_VERSION, host);
|
||||
struct http_message message = {host, port, path, message_buffer};
|
||||
|
||||
return message;
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
#ifndef HTTP_SOCKET_H
|
||||
#define HTTP_SOCKET_H
|
||||
|
||||
#include "../common/http_message.h"
|
||||
|
||||
#define HTTP_VERSION "HTTP/1.1"
|
||||
|
||||
struct http_message build_basic_request(const char *method, const char *host, const char *path, const char *port);
|
||||
|
||||
#endif
|
Loading…
Reference in New Issue