Skip to content

Commit

Permalink
feat: add sc_req_has_header() and sc_req_get_header()
Browse files Browse the repository at this point in the history
  • Loading branch information
orhanemree committed Jun 26, 2024
1 parent 277a144 commit 71fc471
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
9 changes: 7 additions & 2 deletions include/request.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,13 @@ Sc_Request *sc_parse_http_request(char *request);
int __sc_add_header(Sc_Request *req, const char *header_name, const char *header_value);


// TODO: add sc_has_header()
// TODO: add sc_get_header()
// check if Request header has header specified by name
int sc_req_has_header(Sc_Request *req, const char *header_name);


// get copy of header value from Request object if exists, else return NULL
// run free() after you used the value
char *sc_req_get_header(Sc_Request *req, const char *header_name);


// free Request object
Expand Down
27 changes: 27 additions & 0 deletions src/request.c
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Sc_Request *sc_parse_http_request(char *request) {
body_p += 4;

// parse headers
req->header_count = 0;

char *p1, *p2;
char *header = strtok_r(headers, SC_CRLF, &p1);
char *name, *value;
Expand Down Expand Up @@ -98,6 +100,31 @@ int __sc_add_header(Sc_Request *req, const char *header_name, const char *header
}


int sc_req_has_header(Sc_Request *req, const char *header_name) {

for (int i = 0; i < req->header_count; ++i) {
if (strcmp(req->headers[i].name, header_name) == 0) {
return 1;
}
}

return 0;
}


char *sc_req_get_header(Sc_Request *req, const char *header_name) {

for (int i = 0; i < req->header_count; ++i) {
if (strcmp(req->headers[i].name, header_name) == 0) {
// return copy of original value
return strdup(req->headers[i].value);
}
}

return NULL;
}


void sc_free_request(Sc_Request *req) {

for (int i = 0; i < req->header_count; ++i) {
Expand Down
1 change: 0 additions & 1 deletion src/socked.c
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ void __sc_handle_request(Sc_Server *server, int client_socket) {
recv(client_socket, request, SC_MAX_REQ, 0);
printf("==Request==\n%s====\n", request);
Sc_Request *req = sc_parse_http_request(request);
req->header_count = 0;

// prepare response
Sc_Response *res = (Sc_Response *) malloc(sizeof(Sc_Response));
Expand Down

0 comments on commit 71fc471

Please sign in to comment.