requests
This commit is contained in:
@@ -1,8 +1,12 @@
|
||||
#include "http_content_type.h"
|
||||
#include "http_response.h"
|
||||
#include "http_status.h"
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
bool construct_response(HttpResponse __res, char *out) {
|
||||
unsigned long length;
|
||||
@@ -27,8 +31,61 @@ bool construct_response(HttpResponse __res, char *out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
void http_respond(HttpResponse __res) {
|
||||
void http_respond(HttpResponse __res, int clientfd) {
|
||||
char response[BUFSIZ];
|
||||
// TODO: Handle return
|
||||
construct_response(__res, response);
|
||||
|
||||
send(clientfd, response, strlen(response), 0);
|
||||
}
|
||||
|
||||
char *read_file(const char *__path) {
|
||||
if (access(__path, F_OK) != 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
FILE *f = fopen(__path, "r");
|
||||
if (f == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
size_t length = ftell(f);
|
||||
rewind(f);
|
||||
|
||||
char *content = malloc(length * sizeof(char));
|
||||
|
||||
if (content == NULL) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
size_t bytesRead = fread(content, sizeof(char), length, f);
|
||||
content[bytesRead] = 0;
|
||||
|
||||
fclose(f);
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
HttpResponse *from_file(const char *__path) {
|
||||
char *content = read_file(__path);
|
||||
if (content == NULL)
|
||||
return NULL;
|
||||
|
||||
HttpResponse response = {.status_code = HTTP_OK,
|
||||
.content_length = strlen(content),
|
||||
.content_type = HTTP_CT_HTML,
|
||||
.body = content};
|
||||
|
||||
HttpResponse *res = malloc(sizeof(response));
|
||||
*res = response;
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
void free_response(HttpResponse *__res) {
|
||||
if (__res->body != NULL)
|
||||
free(__res->body);
|
||||
|
||||
free(__res);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user