Skip to content

Commit 11cdfea

Browse files
committed
Corrected logic error that was failing tests as per P2P review
1 parent 37fe80a commit 11cdfea

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

src/main/java/org/example/http/HttpResponseBuilder.java

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,31 @@ public void setContentTypeFromFilename(String filename) {
4545
public String build(){
4646
StringBuilder sb = new StringBuilder();
4747
String reason = REASON_PHRASES.getOrDefault(statusCode, "OK");
48+
49+
// Status line
4850
sb.append(PROTOCOL).append(" ").append(statusCode).append(" ").append(reason).append(CRLF);
51+
52+
// User-defined headers
4953
headers.forEach((k,v) -> sb.append(k).append(": ").append(v).append(CRLF));
50-
sb.append("Content-Length: ")
51-
.append(body.getBytes(StandardCharsets.UTF_8).length);
52-
sb.append(CRLF);
53-
sb.append("Connection: close").append(CRLF);
54+
55+
// Only adds Content-Length if not already set
56+
if (!headers.containsKey("Content-Length")) {
57+
sb.append("Content-Length: ")
58+
.append(body.getBytes(StandardCharsets.UTF_8).length)
59+
.append(CRLF);
60+
}
61+
62+
// Only adds Connection if not already set
63+
if (!headers.containsKey("Connection")) {
64+
sb.append("Connection: close").append(CRLF);
65+
}
66+
67+
// Blank line before body
5468
sb.append(CRLF);
69+
70+
// Body
5571
sb.append(body);
72+
5673
return sb.toString();
5774
}
5875
}

0 commit comments

Comments
 (0)