HttpResponse.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. //
  2. // HttpResponse.swift
  3. // Swifter
  4. // Copyright (c) 2015 Damian Kołakowski. All rights reserved.
  5. //
  6. import Foundation
  7. public enum SerializationError: ErrorType {
  8. case InvalidObject
  9. case NotSupported
  10. case EncodingError
  11. }
  12. public protocol Serializer {
  13. func serialize(object: Any) throws -> String
  14. }
  15. public class JSONSerializer : Serializer {
  16. public func serialize(object: Any) throws -> String {
  17. guard let obj = object as? AnyObject where NSJSONSerialization.isValidJSONObject(obj) else {
  18. throw SerializationError.InvalidObject
  19. }
  20. let json = try NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions.PrettyPrinted)
  21. guard let string = String(data: json, encoding: NSUTF8StringEncoding) else {
  22. throw SerializationError.EncodingError
  23. }
  24. return string
  25. }
  26. private static func serialize(object: Any) throws -> String {
  27. let serializer = JSONSerializer()
  28. return try serializer.serialize(object)
  29. }
  30. }
  31. public class XMLSerializer: Serializer {
  32. public func serialize(object: Any) throws -> String {
  33. throw SerializationError.NotSupported
  34. }
  35. private static func serialize(object: Any) throws -> String {
  36. let serializer = XMLSerializer()
  37. return try serializer.serialize(object)
  38. }
  39. }
  40. public class PLISTSerializer: Serializer {
  41. public func serialize(object: Any) throws -> String {
  42. let format = NSPropertyListFormat.XMLFormat_v1_0
  43. guard let obj = object as? AnyObject where NSPropertyListSerialization.propertyList(obj, isValidForFormat: format) else {
  44. throw SerializationError.InvalidObject
  45. }
  46. let plist = try NSPropertyListSerialization.dataWithPropertyList(obj, format: format, options: 0)
  47. guard let string = String(data: plist, encoding: NSUTF8StringEncoding) else {
  48. throw SerializationError.EncodingError
  49. }
  50. return string
  51. }
  52. private static func serialize(object: Any) throws -> String {
  53. let serializer = PLISTSerializer()
  54. return try serializer.serialize(object)
  55. }
  56. }
  57. public enum HttpResponseBody {
  58. case Json(AnyObject)
  59. case Xml(AnyObject)
  60. case Plist(AnyObject)
  61. case Html(String)
  62. case Text(String)
  63. case Custom(Serializer, Any)
  64. func data() -> String? {
  65. do {
  66. switch self {
  67. case .Json(let object):
  68. return try JSONSerializer.serialize(object)
  69. case .Xml(let object):
  70. return try XMLSerializer.serialize(object)
  71. case .Plist(let object):
  72. return try PLISTSerializer.serialize(object)
  73. case .Text(let body):
  74. return body
  75. case .Html(let body):
  76. return "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
  77. case .Custom(let serializer, let object):
  78. return try serializer.serialize(object)
  79. }
  80. } catch {
  81. return "Serialisation error: \(error)"
  82. }
  83. }
  84. }
  85. public enum HttpResponse {
  86. case OK(HttpResponseBody), Created, Accepted
  87. case MovedPermanently(String)
  88. case BadRequest, Unauthorized, Forbidden, NotFound
  89. case InternalServerError
  90. case RAW(Int, String, [String:String]?, NSData)
  91. func statusCode() -> Int {
  92. switch self {
  93. case .OK(_) : return 200
  94. case .Created : return 201
  95. case .Accepted : return 202
  96. case .MovedPermanently : return 301
  97. case .BadRequest : return 400
  98. case .Unauthorized : return 401
  99. case .Forbidden : return 403
  100. case .NotFound : return 404
  101. case .InternalServerError : return 500
  102. case .RAW(let code,_,_,_) : return code
  103. }
  104. }
  105. func reasonPhrase() -> String {
  106. switch self {
  107. case .OK(_) : return "OK"
  108. case .Created : return "Created"
  109. case .Accepted : return "Accepted"
  110. case .MovedPermanently : return "Moved Permanently"
  111. case .BadRequest : return "Bad Request"
  112. case .Unauthorized : return "Unauthorized"
  113. case .Forbidden : return "Forbidden"
  114. case .NotFound : return "Not Found"
  115. case .InternalServerError : return "Internal Server Error"
  116. case .RAW(_,let pharse,_,_) : return pharse
  117. }
  118. }
  119. func headers() -> [String: String] {
  120. var headers = [String:String]()
  121. headers["Server"] = "Swifter \(HttpServer.VERSION)"
  122. switch self {
  123. case .OK(let body):
  124. switch body {
  125. case .Json(_) : headers["Content-Type"] = "application/json"
  126. case .Plist(_) : headers["Content-Type"] = "application/xml"
  127. case .Xml(_) : headers["Content-Type"] = "application/xml"
  128. // 'application/xml' or 'text/xml' ?
  129. // From RFC: http://www.rfc-editor.org/rfc/rfc3023.txt - "If an XML document -- that is, the unprocessed,
  130. // source XML document -- is readable by casual users, text/xml is preferable to application/xml.
  131. // MIME user agents (and web user agents) that do not have explicit support for text/xml will treat it as text/plain,
  132. // for example, by displaying the XML MIME entity as plain text.
  133. case .Html(_) : headers["Content-Type"] = "text/html"
  134. default:break
  135. }
  136. case .MovedPermanently(let location): headers["Location"] = location
  137. case .RAW(_,_, let rawHeaders,_):
  138. if let rawHeaders = rawHeaders {
  139. for (k, v) in rawHeaders {
  140. headers.updateValue(v, forKey: k)
  141. }
  142. }
  143. default:break
  144. }
  145. return headers
  146. }
  147. func body() -> NSData? {
  148. switch self {
  149. case .OK(let body) : return body.data()?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  150. case .RAW(_,_,_, let data) : return data
  151. default : return nil
  152. }
  153. }
  154. }
  155. /**
  156. Makes it possible to compare handler responses with '==', but
  157. ignores any associated values. This should generally be what
  158. you want. E.g.:
  159. let resp = handler(updatedRequest)
  160. if resp == .NotFound {
  161. print("Client requested not found: \(request.url)")
  162. }
  163. */
  164. func ==(inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
  165. return inLeft.statusCode() == inRight.statusCode()
  166. }