/
routes.swift
241 lines (209 loc) · 7.18 KB
/
routes.swift
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import Vapor
import _Vapor3
struct Creds: Content {
var email: String
var password: String
}
public func routes(_ app: Application) throws {
app.on(.POST, "ping") { req in
return "123" as StaticString
}
// ( echo -e 'POST /slow-stream HTTP/1.1\r\nContent-Length: 1000000000\r\n\r\n'; dd if=/dev/zero; ) | nc localhost 8080
app.on(.POST, "slow-stream", body: .stream) { req -> Future<String> in
let done = req.eventLoop.makePromise(of: String.self)
var total = 0
req.body.drain { result in
let promise = req.eventLoop.makePromise(of: Void.self)
switch result {
case .buffer(let buffer):
req.eventLoop.scheduleTask(in: .milliseconds(1000)) {
total += buffer.readableBytes
promise.succeed(())
}
case .error(let error):
done.fail(error)
case .end:
promise.succeed(())
done.succeed(total.description)
}
// manually return pre-completed future
// this should balloon in memory
// return req.eventLoop.makeSucceededFuture(())
// return real future that indicates bytes were handled
// this should use very little memory
return promise.futureResult
}
return done.futureResult
}
app.post("login") { req -> String in
let creds = try req.content.decode(Creds.self)
return "\(creds)"
}
app.on(.POST, "large-file", body: .collect(maxSize: 1_000_000_000)) { req -> String in
return req.body.data?.readableBytes.description ?? "none"
}
app.get("json") { req -> [String: String] in
return ["foo": "bar"]
}.description("returns some test json")
app.webSocket("ws") { req, ws in
ws.onText { ws, text in
ws.send(text.reversed())
if text == "close" {
ws.close(promise: nil)
}
}
let ip = req.remoteAddress?.description ?? "<no ip>"
ws.send("Hello 👋 \(ip)")
}
app.on(.POST, "file", body: .stream) { req -> EventLoopFuture<String> in
let promise = req.eventLoop.makePromise(of: String.self)
req.body.drain { result in
switch result {
case .buffer(let buffer):
debugPrint(buffer)
case .error(let error):
promise.fail(error)
case .end:
promise.succeed("Done")
}
return req.eventLoop.makeSucceededFuture(())
}
return promise.futureResult
}
app.get("shutdown") { req -> HTTPStatus in
guard let running = req.application.running else {
throw Abort(.internalServerError)
}
running.stop()
return .ok
}
let cache = MemoryCache()
app.get("cache", "get", ":key") { req -> String in
guard let key = req.parameters.get("key") else {
throw Abort(.internalServerError)
}
return "\(key) = \(cache.get(key) ?? "nil")"
}
app.get("cache", "set", ":key", ":value") { req -> String in
guard let key = req.parameters.get("key") else {
throw Abort(.internalServerError)
}
guard let value = req.parameters.get("value") else {
throw Abort(.internalServerError)
}
cache.set(key, to: value)
return "\(key) = \(value)"
}
app.get("hello", ":name") { req in
return req.parameters.get("name") ?? "<nil>"
}
app.get("search") { req in
return req.query["q"] ?? "none"
}
let sessions = app.grouped("sessions")
.grouped(app.sessions.middleware)
sessions.get("set", ":value") { req -> HTTPStatus in
req.session.data["name"] = req.parameters.get("value")
return .ok
}
sessions.get("get") { req -> String in
req.session.data["name"] ?? "n/a"
}
sessions.get("del") { req -> String in
req.session.destroy()
return "done"
}
app.get("client") { req in
return req.client.get("http://httpbin.org/status/201").map { $0.description }
}
app.get("client-json") { req -> EventLoopFuture<String> in
struct HTTPBinResponse: Decodable {
struct Slideshow: Decodable {
var title: String
}
var slideshow: Slideshow
}
return req.client.get("http://httpbin.org/json")
.flatMapThrowing { try $0.content.decode(HTTPBinResponse.self) }
.map { $0.slideshow.title }
}
let users = app.grouped("users")
users.get { req in
return "users"
}
users.get(":userID") { req in
return req.parameters.get("userID") ?? "no id"
}
app.directory.viewsDirectory = "/Users/tanner/Desktop"
app.get("view") { req in
req.view.render("hello.txt", ["name": "world"])
}
app.get("error") { req -> String in
throw TestError()
}
app.get("secret") { (req) -> EventLoopFuture<String> in
return Environment
.secret(key: "PASSWORD_SECRET", fileIO: req.application.fileio, on: req.eventLoop)
.unwrap(or: Abort(.badRequest))
}
app.on(.POST, "max-256", body: .collect(maxSize: 256)) { req -> HTTPStatus in
print("in route")
return .ok
}
app.on(.POST, "upload", body: .stream) { req -> EventLoopFuture<HTTPStatus> in
return req.application.fileio.openFile(
path: "/Users/tanner/Desktop/foo.txt",
mode: .write,
flags: .allowFileCreation(),
eventLoop: req.eventLoop
).flatMap { fileHandle in
let promise = req.eventLoop.makePromise(of: HTTPStatus.self)
req.body.drain { part in
switch part {
case .buffer(let buffer):
return req.application.fileio.write(
fileHandle: fileHandle,
buffer: buffer,
eventLoop: req.eventLoop
)
case .error(let error):
promise.fail(error)
try! fileHandle.close()
return req.eventLoop.makeSucceededFuture(())
case .end:
promise.succeed(.ok)
try! fileHandle.close()
return req.eventLoop.makeSucceededFuture(())
}
}
return promise.futureResult
}
}
}
struct TestError: AbortError, DebuggableError {
var status: HTTPResponseStatus {
.internalServerError
}
var reason: String {
"This is a test."
}
var source: ErrorSource?
var stackTrace: StackTrace?
init(
file: String = #file,
function: String = #function,
line: UInt = #line,
column: UInt = #column,
range: Range<UInt>? = nil,
stackTrace: StackTrace? = .capture(skip: 1)
) {
self.source = .init(
file: file,
function: function,
line: line,
column: column,
range: range
)
self.stackTrace = stackTrace
}
}