Skip to content

Instantly share code, notes, and snippets.

@sakshamgurung
Created February 7, 2022 15:06
Show Gist options
  • Save sakshamgurung/d4fdc59ea35db53ec8abc7f2cf695ea6 to your computer and use it in GitHub Desktop.
Save sakshamgurung/d4fdc59ea35db53ec8abc7f2cf695ea6 to your computer and use it in GitHub Desktop.
Connection class part III
// 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