-
Notifications
You must be signed in to change notification settings - Fork 554
Expand file tree
/
Copy pathHttpResponse.swift
More file actions
188 lines (172 loc) · 6.47 KB
/
HttpResponse.swift
File metadata and controls
188 lines (172 loc) · 6.47 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//
// HttpResponse.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public enum SerializationError: Error {
case invalidObject
case notSupported
}
public protocol HttpResponseBodyWriter {
func write(_ file: String.File) throws
func write(_ data: [UInt8]) throws
func write(_ data: ArraySlice<UInt8>) throws
func write(_ data: NSData) throws
func write(_ data: Data) throws
}
public enum HttpResponseBody {
case json(Any)
case html(String)
case htmlBody(String)
case text(String)
case data(Data, contentType: String? = nil)
case custom(Any, (Any) throws -> String)
func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
do {
switch self {
case .json(let object):
guard JSONSerialization.isValidJSONObject(object) else {
throw SerializationError.invalidObject
}
let data = try JSONSerialization.data(withJSONObject: object)
return (data.count, {
try $0.write(data)
})
case .text(let body):
let data = [UInt8](body.utf8)
return (data.count, {
try $0.write(data)
})
case .html(let html):
let data = [UInt8](html.utf8)
return (data.count, {
try $0.write(data)
})
case .htmlBody(let body):
let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
let data = [UInt8](serialised.utf8)
return (data.count, {
try $0.write(data)
})
case .data(let data, _):
return (data.count, {
try $0.write(data)
})
case .custom(let object, let closure):
let serialised = try closure(object)
let data = [UInt8](serialised.utf8)
return (data.count, {
try $0.write(data)
})
}
} catch {
let data = [UInt8]("Serialisation error: \(error)".utf8)
return (data.count, {
try $0.write(data)
})
}
}
}
// swiftlint:disable cyclomatic_complexity
public enum HttpResponse {
case switchProtocols([String: String], (Socket) -> Void)
case ok(HttpResponseBody), created, accepted
case movedPermanently(String)
case movedTemporarily(String)
case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound, notAcceptable
case tooManyRequests
case internalServerError
case raw(Int, String, [String: String]?, ((HttpResponseBodyWriter) throws -> Void)? )
public var statusCode: Int {
switch self {
case .switchProtocols : return 101
case .ok : return 200
case .created : return 201
case .accepted : return 202
case .movedPermanently : return 301
case .movedTemporarily : return 307
case .badRequest : return 400
case .unauthorized : return 401
case .forbidden : return 403
case .notFound : return 404
case .notAcceptable : return 406
case .tooManyRequests : return 429
case .internalServerError : return 500
case .raw(let code, _, _, _) : return code
}
}
public var reasonPhrase: String {
switch self {
case .switchProtocols : return "Switching Protocols"
case .ok : return "OK"
case .created : return "Created"
case .accepted : return "Accepted"
case .movedPermanently : return "Moved Permanently"
case .movedTemporarily : return "Moved Temporarily"
case .badRequest : return "Bad Request"
case .unauthorized : return "Unauthorized"
case .forbidden : return "Forbidden"
case .notFound : return "Not Found"
case .notAcceptable : return "Not Acceptable"
case .tooManyRequests : return "Too Many Requests"
case .internalServerError : return "Internal Server Error"
case .raw(_, let phrase, _, _) : return phrase
}
}
public func headers() -> [String: String] {
var headers = ["Server": "Swifter \(HttpServer.VERSION)"]
switch self {
case .switchProtocols(let switchHeaders, _):
for (key, value) in switchHeaders {
headers[key] = value
}
case .ok(let body):
switch body {
case .json: headers["Content-Type"] = "application/json"
case .html: headers["Content-Type"] = "text/html"
case .data(_, let contentType): headers["Content-Type"] = contentType
default:break
}
case .movedPermanently(let location):
headers["Location"] = location
case .movedTemporarily(let location):
headers["Location"] = location
case .raw(_, _, let rawHeaders, _):
if let rawHeaders = rawHeaders {
for (key, value) in rawHeaders {
headers.updateValue(value, forKey: key)
}
}
default:break
}
return headers
}
func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) {
switch self {
case .ok(let body) : return body.content()
case .badRequest(let body) : return body?.content() ?? (-1, nil)
case .raw(_, _, _, let writer) : return (-1, writer)
default : return (-1, nil)
}
}
func socketSession() -> ((Socket) -> Void)? {
switch self {
case .switchProtocols(_, let handler) : return handler
default: return nil
}
}
}
/**
Makes it possible to compare handler responses with '==', but
ignores any associated values. This should generally be what
you want. E.g.:
let resp = handler(updatedRequest)
if resp == .NotFound {
print("Client requested not found: \(request.url)")
}
*/
func == (inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
return inLeft.statusCode == inRight.statusCode
}