Created
February 7, 2022 15:06
-
-
Save sakshamgurung/d4fdc59ea35db53ec8abc7f2cf695ea6 to your computer and use it in GitHub Desktop.
Connection class part III
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// continue Connection class... | |
// helper method: getting the path to access the requested resource/information hosted by the server (aka routing) | |
private static Path getFilePath(String path) { | |
Matcher match = Pattern.compile("/watch/").matcher(path); | |
if(match.find()){ | |
// replacing "watch" with "resources" because we have our videos inside that directory | |
path = path.replaceAll("/watch/", "./"); | |
path = path + ".mp4"; | |
return Paths.get(path); | |
} | |
if ("/".equals(path)) { | |
path = "index.html"; | |
}else if("/cats".equals(path)){ | |
path = "cats.html"; | |
} | |
return Paths.get("./public/", path); | |
} | |
// helper method: guessing the resource extension eg: .html, .mp4 etc | |
private static String guessContentType(Path filePath) throws IOException { | |
return Files.probeContentType(filePath); | |
} | |
// helper method: creating response message for the client's request | |
private void sendResponse(String status, String contentType, String additional_header, byte[] content) throws IOException { | |
byte[] response = ( | |
"HTTP/1.1 " + status + "\r\n" | |
+ "Content-Type: " + contentType + "\r\n" | |
+ additional_header | |
+ "\r\n").getBytes("UTF-8"); | |
out.write(response, 0, response.length); | |
out.write(content, 0, content.length); | |
out.write("\r\n\r\n".getBytes("UTF-8")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment