Skip to content
Open
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 43 additions & 7 deletions src/server.c
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,28 @@ int send_response(int fd, char *header, char *content_type, void *body, int cont
{
const int max_response_size = 262144;
char response[max_response_size];

// Build HTTP response and store it in response
int response_length = strlen(body);

///////////////////
// IMPLEMENT ME! //
///////////////////
//time
time_t rawtime;
struct tm *info;
time (&rawtime);
info = localtime(&rawtime);

//build header
sprintf(response,
"%s\n"
"Date: %s\n"
"Content-type: %s\n"
"Content-length: %d\n"
"Connection: close\n"
"\n"
"%s\n", header, asctime(info), content_type, content_length, body
);

// Send it all!
int rv = send(fd, response, response_length, 0);
Expand All @@ -76,16 +92,18 @@ int send_response(int fd, char *header, char *content_type, void *body, int cont
void get_d20(int fd)
{
// Generate a random number between 1 and 20 inclusive

///////////////////
// IMPLEMENT ME! //
///////////////////
char str;
int random_number = rand() % 21; //num = (rand() % (upper – lower + 1)) + lower
sprintf(str, "%d\n", random_number);

// Use send_response() to send it back as text/plain data

///////////////////
// IMPLEMENT ME! //
///////////////////
send_response(fd, "HTTP/1.1 200 OK", "text/plain", str, strlen(str));
}

/**
Expand Down Expand Up @@ -122,6 +140,9 @@ void get_file(int fd, struct cache *cache, char *request_path)
///////////////////
// IMPLEMENT ME! //
///////////////////
(void)fd;
(void)cache;
(void)request_path;
}

/**
Expand All @@ -135,13 +156,15 @@ char *find_start_of_body(char *header)
///////////////////
// IMPLEMENT ME! // (Stretch)
///////////////////
(void)header;
}

/**
* Handle HTTP request and send response
*/
void handle_http_request(int fd, struct cache *cache)
{
(void)cache; //rememember to remove all these voids. reeeeeeeeemember!
const int request_buffer_size = 65536; // 64K
char request[request_buffer_size];

Expand All @@ -153,20 +176,33 @@ void handle_http_request(int fd, struct cache *cache)
return;
}


///////////////////
// IMPLEMENT ME! //
///////////////////

// Read the three components of the first request line
char method[512];
char path[8192];

sscanf(request, "%s %s", method, path);
printf("method: \"%s\"\n", method);
printf("path: \"%s\"\n", path);

// If GET, handle the get endpoints

// Check if it's /d20 and handle that special case
// Otherwise serve the requested file by calling get_file()


if (strcmp(method, "GET") == 0)
if (strcmp(path, "/d20") == 0) //strcmp returns 0 if equal
{
get_d20(fd);
}
else
{
resp_404(fd);
}

// (Stretch) If POST, handle the post request
//if (strcmp(method, "POST") == 0)
}

/**
Expand Down