postnummer-app/backend/http.c

56 lines
1.4 KiB
C
Raw Normal View History

2023-02-09 12:50:26 +00:00
#include "http.h"
2023-02-09 14:55:57 +00:00
#include <stdbool.h>
#include <stdio.h>
2023-02-09 12:50:26 +00:00
#include <stdlib.h>
2023-02-09 14:55:57 +00:00
#include <string.h>
2023-02-09 12:50:26 +00:00
2023-02-09 14:55:57 +00:00
typedef struct {
const char* message;
size_t message_size;
size_t i;
} HttpRequestHeaderParser;
2023-02-09 12:50:26 +00:00
2023-02-09 14:55:57 +00:00
HttpMethod parse_method(HttpRequestHeaderParser* parser)
{
if (parser->i + 3 < parser->message_size && strncmp(&parser->message[0], "GET", 3)) {
parser->i += 3;
return HttpMethodGet;
} else if (parser->i + 4 < parser->message_size && strncmp(&parser->message[0], "POST", 4)) {
parser->i += 4;
return HttpMethodPost;
2023-02-09 12:50:26 +00:00
} else {
2023-02-09 14:55:57 +00:00
printf("error: http parser: failed to parse http method\n");
exit(1);
}
}
void skip_char(HttpRequestHeaderParser* parser, char value)
{
if (parser->message[parser->i] != value) {
printf("error: http parser: unexpected character, expected ' '\n");
exit(1);
}
parser->i += 1;
if (parser->i >= parser->message_size) {
printf("error: http parser: unexpected end\n");
2023-02-09 12:50:26 +00:00
exit(1);
}
2023-02-09 14:55:57 +00:00
}
2023-02-09 12:50:26 +00:00
2023-02-09 14:55:57 +00:00
typedef struct {
size_t begin, length;
} PathSpan;
HttpRequestHeader parse_http_request_header(const char* message, size_t message_size)
{
HttpRequestHeaderParser parser = (HttpRequestHeaderParser) {
.message = message,
.message_size = message_size,
.i = 0,
};
HttpMethod method = parse_method(&parser);
skip_char(&parser, ' ');
2023-02-09 12:50:26 +00:00
return (HttpRequestHeader) { 0 };
}