Our server code uses a series of if statements to determine the proper media type based only on the requested file's extension. This isn't a perfect solution, but it is a common one, and it works for our purposes.
The code to determine a file's media type is as follows:
/*web_server.c except*/
const char *get_content_type(const char* path) {
const char *last_dot = strrchr(path, '.');
if (last_dot) {
if (strcmp(last_dot, ".css") == 0) return "text/css";
if (strcmp(last_dot, ".csv") == 0) return "text/csv";
if (strcmp(last_dot, ".gif") == 0) return "image/gif";
if (strcmp(last_dot, ".htm") == 0) return "text/html";
if (strcmp(last_dot, ".html") == 0) return "text/html";
if (strcmp(last_dot, ".ico") == 0) return "image/x-icon";
if (strcmp(last_dot, ".jpeg") == 0) return "image/jpeg";
if (strcmp(last_dot, ".jpg") == 0) return "image/jpeg";
if (strcmp(last_dot, ".js") == 0) return "application/javascript";
if (strcmp(last_dot, ".json") == 0) return "application/json";
if (strcmp(last_dot, ".png") == 0) return "image/png";
if (strcmp(last_dot, ".pdf") == 0) return "application/pdf";
if (strcmp(last_dot, ".svg") == 0) return "image/svg+xml";
if (strcmp(last_dot, ".txt") == 0) return "text/plain";
}
return "application/octet-stream";
}
The get_content_type() function works by matching the filename extension to a list of known extensions. This is done by using the strrchr() function to find the last dot (.) in the filename. If a dot is found, then strcmp() is used to check for a match on each extension. When a match is found, the proper media type is returned. Otherwise, the default of application/octet-stream is returned instead.
Let's continue building helper functions for our server.