HttpResponse.swift 5.8 KB

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