HttpResponse.swift~ 5.8 KB

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