summaryrefslogtreecommitdiff
path: root/net.c
diff options
context:
space:
mode:
authorcflip <cflip@cflip.net>2023-05-30 12:31:34 -0600
committercflip <cflip@cflip.net>2023-05-30 12:31:34 -0600
commit8dbdf132ea82a567d7cef856469fd47c511b4191 (patch)
tree66d87095b94b90a1a66946c0b514cfbe75ae1f10 /net.c
parent775c4157994ee0ebe9bd951a99bc5d7558128ba4 (diff)
Refactor response building code
This new strategy involves finding the local file path for the given URI, determining what method to use to fulfill the request (read file from disk, use php-cgi, or error), then it writes the response to the client socket.
Diffstat (limited to 'net.c')
-rw-r--r--net.c36
1 files changed, 30 insertions, 6 deletions
diff --git a/net.c b/net.c
index c7d075a..ce19fc7 100644
--- a/net.c
+++ b/net.c
@@ -53,20 +53,44 @@ int initialize_server(int port)
void handle_connection(int connfd)
{
- const char *header = "HTTP/1.1 200 OK\r\n";
char readbuf[CFWS_MAXREAD];
struct http_request req;
+ char *filepath;
+ enum http_res_code res_code;
+ enum serve_method method;
+
+ /* Read and parse the HTTP request */
memset(readbuf, 0, CFWS_MAXREAD);
read(connfd, readbuf, CFWS_MAXREAD - 1);
-
req = http_parse_request(readbuf);
- write(connfd, header, strlen(header));
- if (file_handle_request(&req, connfd) != 0) {
- const char *msg = "\r\nCould not find the specified file.";
- write(connfd, msg, strlen(msg));
+ /* Get the local file path for the given URI. */
+ filepath = file_path_for_uri(req.uri);
+
+ printf("GET %s : %s\n", req.uri, filepath);
+
+ /* Determine the method that should be used to serve this file */
+ method = file_method_for_path(filepath, &res_code);
+
+ /* Write the HTTP response status and any required headers */
+ http_response_statusline(res_code, connfd);
+
+ /* Use the chosen method to fill in the rest of the response */
+ switch (method) {
+ case SERVE_METHOD_FILE:
+ file_read(filepath, connfd);
+ break;
+ case SERVE_METHOD_PHP:
+ file_read_php(filepath, connfd);
+ break;
+ case SERVE_METHOD_ERROR: {
+ const char *errmsg = "Content-Type: text/plain\r\n\r\nEpic fail";
+ write(connfd, errmsg, strlen(errmsg));
+ break;
+ }
}
+ free(filepath);
http_free_request(&req);
}