-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestHandler.java
More file actions
40 lines (29 loc) · 1.08 KB
/
Copy pathRequestHandler.java
File metadata and controls
40 lines (29 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package httpserver;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class RequestHandler {
protected Path basedir;
public RequestHandler(String basedir) {
this.basedir = Paths.get(basedir).toAbsolutePath().normalize();
}
public HttpResponse handle(HttpRequest request) throws HttpError {
Path filepath = Paths.get(basedir.toString(), request.path).normalize();
// Check the path
if (!filepath.startsWith(basedir)) {
// The path is outside of the basedir.
throw new HttpError(HttpStatus.Forbidden(), request.path );
}
if (!filepath.toFile().exists()) {
// The file or directory does not exist.
throw new HttpError(HttpStatus.NotFound(), request.path );
}
HttpResponse response = null;
if (filepath.toFile().isDirectory()) {
response = new DirectoryResponse(request, filepath, basedir);
} else {
response = new FileResponse(request, filepath);
}
return response;
}
}