Skip to content

Commit 4a26825

Browse files
committed
Refactor into smaller methods
1 parent 872684e commit 4a26825

File tree

3 files changed

+25
-8
lines changed

3 files changed

+25
-8
lines changed

src/main/java/httpserver/App.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public static void main(String[] args) {
1212
int port = Integer.parseInt(args[1]);
1313
String fileDirectory = args[3];
1414
Path root = Files.getPath(fileDirectory);
15+
1516
try {
1617
ServerSocket serverSocket = new ServerSocket(port);
1718
while (true) {

src/main/java/httpserver/SocketHandler.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,14 @@ public SocketHandler(Path root) {
1818

1919
public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
2020
Response response;
21+
2122
try {
2223
Request request = new RequestParser().parse(inputStream);
2324
response = new GeneralResponder().respond(root, request);
2425
} catch (Exception e) {
2526
response = new NotFoundResponse();
2627
}
28+
2729
new ResponseWriter().write(response, outputStream);
2830
}
2931
}

src/main/java/httpserver/responder/GetResponder.java

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,32 @@ public Response respond(Path root, Request request) {
1717

1818
if (Files.pathExists(path)) {
1919
if (Files.isFile(path)) {
20-
byte[] payload = Files.fileContents(path);
21-
return new OkResponse(payload);
20+
return responseForFile(path);
2221
} else {
23-
Path[] paths = Files.directoryContents(path);
24-
String result = "";
25-
for (Path subPath: paths) {
26-
result = result + linkString(root, subPath);
27-
}
28-
return new OkResponse(result.getBytes());
22+
return responseForDir(root, path);
2923
}
3024
} else {
3125
return new NotFoundResponse();
3226
}
3327
}
28+
29+
private Response responseForDir(Path root, Path path) {
30+
Path[] paths = Files.directoryContents(path);
31+
String result = htmlLinksForContents(root, paths);
32+
return new OkResponse(result.getBytes());
33+
}
34+
35+
private String htmlLinksForContents(Path root, Path[] paths) {
36+
String result = "";
37+
for (Path subPath: paths) {
38+
result = result + linkString(root, subPath);
39+
}
40+
return result;
41+
}
42+
43+
private Response responseForFile(Path path) {
44+
byte[] payload = Files.fileContents(path);
45+
return new OkResponse(payload);
46+
}
47+
3448
}

0 commit comments

Comments
 (0)