HttpResponse.swift 5.9 KB

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