Skip to content

Commit a99575f

Browse files
committed
*starting to add some helper methods to make sending content a little more easily
1 parent 2fcfb84 commit a99575f

File tree

2 files changed

+22
-14
lines changed

2 files changed

+22
-14
lines changed

example/main.swift

+3-14
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,9 @@ while (true) {
2424

2525
let clientSocket = accept(server.serverSocket, nil, nil)
2626

27-
let msg = "Hello World"
28-
let contentLength = msg.utf8.count
29-
30-
server.echo(clientSocket, "HTTP/1.1 200 OK\n")
31-
server.echo(clientSocket, "Server: Swift Web Server\n")
32-
server.echo(clientSocket, "Content-length: \(contentLength)\n")
33-
server.echo(clientSocket, "Content-type: text-plain\n")
34-
server.echo(clientSocket, "Connection: close\n")
35-
server.echo(clientSocket, "\r\n")
36-
37-
server.echo(clientSocket, msg)
38-
39-
print("Response sent: '\(msg)' - Length: \(contentLength)")
40-
27+
let msg = "<h1>Hello World</h1>"
28+
// server.send_http(clientSocket, msg, content_type: "text-plain")//sends plain text
29+
server.send_http(clientSocket, msg)//defaults to html
4130
shutdown(clientSocket, Int32(SHUT_RDWR))
4231
close(clientSocket)
4332
}

http/HTTP.swift

+19
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,25 @@ public class HTTP {
1313
return UnsafeMutablePointer<sockaddr>(p)
1414
}
1515

16+
public func send_http(socket: Int32, _ output: String, content_type: String = "text/html; charset=UTF-8", status_code: String = "200 OK") {
17+
let contentLength = output.utf8.count
18+
19+
send_http_header(socket, code: status_code, content_length: "\(contentLength)", type: content_type)
20+
echo(socket, output)
21+
22+
print("Response sent: '\(output)' - Length: \(contentLength)")
23+
24+
}
25+
26+
public func send_http_header(socket: Int32, code: String = "200 OK", server_name: String = "Swift Web Server", content_length: String, type: String = "text-plain") {
27+
echo(socket, "HTTP/1.1 \(code)\n")
28+
echo(socket, "Server: \(server_name)\n")
29+
echo(socket, "Content-length: \(content_length)\n")
30+
echo(socket, "Content-type: \(type)\n")
31+
echo(socket, "Connection: close\n")
32+
echo(socket, "\r\n")
33+
}
34+
1635
public func echo(socket: Int32, _ output: String) {
1736
output.withCString { (bytes) in
1837
#if os(Linux)

0 commit comments

Comments
 (0)