1
0

HttpResponse.swift 6.2 KB

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