Skip to content

Commit adb64b4

Browse files
committed
Correctly calculate Content-Length as a byte size
The HTTP server currently is calculating Content-Length as a naive character count, but the header is supposed to be the byte size of the response contents. In the case of "Hello World", the two are equivalent, but, if the response contained special characters, the Content-Length would be incorrect: ```swift print("moose".characters.count) // 5 print("møøse".characters.count) // 5 print("møøse".utf8.count) // 7 ``` For semantic reasons, and for people who are copying the source to serve their own custom responses, we should provide the correct byte length. Signed-off-by: David Celis <[email protected]>
1 parent 5c32dbc commit adb64b4

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

Sources/http.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,17 @@ public class HTTP {
4949
let clientSocket = accept(serverSocket, nil, nil)
5050

5151
let msg = "Hello World"
52+
let contentLength = msg.utf8.count
5253

5354
echo(clientSocket, "HTTP/1.1 200 OK\n")
5455
echo(clientSocket, "Server: Swift Web Server\n")
55-
echo(clientSocket, "Content-length: \(msg.characters.count)\n")
56+
echo(clientSocket, "Content-length: \(contentLength)\n")
5657
echo(clientSocket, "Content-type: text-plain\n")
5758
echo(clientSocket, "\r\n")
5859

5960
echo(clientSocket, msg)
6061

61-
print("Response sent: '\(msg)' - Length: \(msg.characters.count)")
62+
print("Response sent: '\(msg)' - Length: \(contentLength)")
6263

6364
close(clientSocket)
6465
}

0 commit comments

Comments
 (0)