Skip to content

Commit

Permalink
Added Cookies Middleware #22
Browse files Browse the repository at this point in the history
  • Loading branch information
sauliusgrigaitis committed Mar 13, 2016
1 parent 7e318cf commit f1f636e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
19 changes: 19 additions & 0 deletions Sources/Swifton/CookiesMiddleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Inquiline

public class CookiesMiddleware: Middleware {
public func call(request: Request, _ closure: Request -> Response) -> Response {
var newRequest = request
if let rawCookie = newRequest["Cookie"] {
let cookiePairs = rawCookie.characters.split(";").flatMap(String.init)
for cookie in cookiePairs {
let keyValue = cookie.characters.split("=").flatMap(String.init)
newRequest.cookies[keyValue[0]] = keyValue[1]
}
}

var response = closure(newRequest)

response["Set-Cookie"] = response.cookies.map { $0 + "=" + $1 }.joinWithSeparator(";")
return response
}
}
6 changes: 4 additions & 2 deletions Sources/Swifton/Router.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,10 @@ public class Router {
}

public func respond(requestType: RequestType) -> ResponseType {
let request = requestType as? Request ?? Request(method: requestType.method, path: requestType.path, headers: requestType.headers, body: requestType.body)
return ParametersMiddleware().call(request, resolveRoute)
let request = requestType as? Request ?? Request(method: requestType.method, path: requestType.path, headers: requestType.headers, body: requestType.body)
return ParametersMiddleware().call(request) {
CookiesMiddleware().call($0, self.resolveRoute)
}
}

public func resolveRoute(request: Request) -> Response {
Expand Down

0 comments on commit f1f636e

Please sign in to comment.