HttpResponse.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. //
  2. // HttpResponse.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public enum SerializationError: ErrorType {
  9. case InvalidObject
  10. case NotSupported
  11. }
  12. public protocol HttpResponseBodyWriter {
  13. func write(data: [UInt8])
  14. func write(data: ArraySlice<UInt8>)
  15. }
  16. public enum HttpResponseBody {
  17. case Json(AnyObject)
  18. case Html(String)
  19. case Text(String)
  20. case Custom(Any, (Any) throws -> String)
  21. func content() -> (Int, (HttpResponseBodyWriter throws -> Void)?) {
  22. do {
  23. switch self {
  24. case .Json(let object):
  25. guard NSJSONSerialization.isValidJSONObject(object) else {
  26. throw SerializationError.InvalidObject
  27. }
  28. let json = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted)
  29. let data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
  30. return (data.count, {
  31. $0.write(data)
  32. })
  33. case .Text(let body):
  34. let data = [UInt8](body.utf8)
  35. return (data.count, {
  36. $0.write(data)
  37. })
  38. case .Html(let body):
  39. let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
  40. let data = [UInt8](serialised.utf8)
  41. return (data.count, {
  42. $0.write(data)
  43. })
  44. case .Custom(let object, let closure):
  45. let serialised = try closure(object)
  46. let data = [UInt8](serialised.utf8)
  47. return (data.count, {
  48. $0.write(data)
  49. })
  50. }
  51. } catch {
  52. let data = [UInt8]("Serialisation error: \(error)".utf8)
  53. return (data.count, {
  54. $0.write(data)
  55. })
  56. }
  57. }
  58. }
  59. public enum HttpResponse {
  60. case SwitchProtocols([String: String], Socket -> Void)
  61. case OK(HttpResponseBody), Created, Accepted
  62. case MovedPermanently(String)
  63. case BadRequest(HttpResponseBody?), Unauthorized, Forbidden, NotFound
  64. case InternalServerError
  65. case RAW(Int, String, [String:String]?, (HttpResponseBodyWriter -> Void)? )
  66. func statusCode() -> Int {
  67. switch self {
  68. case .SwitchProtocols(_, _) : return 101
  69. case .OK(_) : return 200
  70. case .Created : return 201
  71. case .Accepted : return 202
  72. case .MovedPermanently : return 301
  73. case .BadRequest(_) : return 400
  74. case .Unauthorized : return 401
  75. case .Forbidden : return 403
  76. case .NotFound : return 404
  77. case .InternalServerError : return 500
  78. case .RAW(let code, _ , _, _) : return code
  79. }
  80. }
  81. func reasonPhrase() -> String {
  82. switch self {
  83. case .SwitchProtocols(_, _) : return "Switching Protocols"
  84. case .OK(_) : return "OK"
  85. case .Created : return "Created"
  86. case .Accepted : return "Accepted"
  87. case .MovedPermanently : return "Moved Permanently"
  88. case .BadRequest(_) : return "Bad Request"
  89. case .Unauthorized : return "Unauthorized"
  90. case .Forbidden : return "Forbidden"
  91. case .NotFound : return "Not Found"
  92. case .InternalServerError : return "Internal Server Error"
  93. case .RAW(_, let phrase, _, _) : return phrase
  94. }
  95. }
  96. func headers() -> [String: String] {
  97. var headers = ["Server" : "Swifter \(HttpServer.VERSION)"]
  98. switch self {
  99. case .SwitchProtocols(let switchHeaders, _):
  100. for (key, value) in switchHeaders {
  101. headers[key] = value
  102. }
  103. case .OK(let body):
  104. switch body {
  105. case .Json(_) : headers["Content-Type"] = "application/json"
  106. case .Html(_) : headers["Content-Type"] = "text/html"
  107. default:break
  108. }
  109. case .MovedPermanently(let location):
  110. headers["Location"] = location
  111. case .RAW(_, _, let rawHeaders, _):
  112. if let rawHeaders = rawHeaders {
  113. for (k, v) in rawHeaders {
  114. headers.updateValue(v, forKey: k)
  115. }
  116. }
  117. default:break
  118. }
  119. return headers
  120. }
  121. func content() -> (length: Int, write: (HttpResponseBodyWriter throws -> Void)?) {
  122. switch self {
  123. case .OK(let body) : return body.content()
  124. case .BadRequest(let body) : return body?.content() ?? (-1, nil)
  125. case .RAW(_, _, _, let writer) : return (-1, writer)
  126. default : return (-1, nil)
  127. }
  128. }
  129. func socketSession() -> (Socket -> Void)? {
  130. switch self {
  131. case SwitchProtocols(_, let handler) : return handler
  132. default: return nil
  133. }
  134. }
  135. }
  136. /**
  137. Makes it possible to compare handler responses with '==', but
  138. ignores any associated values. This should generally be what
  139. you want. E.g.:
  140. let resp = handler(updatedRequest)
  141. if resp == .NotFound {
  142. print("Client requested not found: \(request.url)")
  143. }
  144. */
  145. func ==(inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
  146. return inLeft.statusCode() == inRight.statusCode()
  147. }