Skip to content

Instantly share code, notes, and snippets.

@gtranchedone
Created May 30, 2017 16:13
Show Gist options
  • Save gtranchedone/dc2376f12efe48b9aebe6749484e913b to your computer and use it in GitHub Desktop.
Save gtranchedone/dc2376f12efe48b9aebe6749484e913b to your computer and use it in GitHub Desktop.
Respond to different requests in Vapor
public func respond(to request: Request, with responses: [ContentType : ResponseRepresentable]) throws -> ResponseRepresentable {
let contentType: ContentType
let _ = request.accept.prefers("html")
if let header = request.accept.first {
var requestedContentType = ContentType.from(string: header.mediaType)
if requestedContentType == .any {
if let requestContentType = request.contentType {
requestedContentType = ContentType.from(string: requestContentType)
}
else {
requestedContentType = .html
}
}
contentType = requestedContentType
}
else {
contentType = ContentType.html
}
guard let response = responses[contentType] else { throw Abort.badRequest }
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment