1
0

HttpResponse.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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: Error {
  9. case invalidObject
  10. case notSupported
  11. }
  12. public protocol HttpResponseBodyWriter {
  13. func write(_ file: String.File) throws
  14. func write(_ data: [UInt8]) throws
  15. func write(_ data: ArraySlice<UInt8>) throws
  16. func write(_ data: NSData) throws
  17. func write(_ data: Data) throws
  18. }
  19. public enum HttpResponseBody {
  20. case json(Any)
  21. case html(String)
  22. case htmlBody(String)
  23. case text(String)
  24. case data(Data, contentType: String? = nil)
  25. case custom(Any, (Any) throws -> String)
  26. func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
  27. do {
  28. switch self {
  29. case .json(let object):
  30. guard JSONSerialization.isValidJSONObject(object) else {
  31. throw SerializationError.invalidObject
  32. }
  33. let data = try JSONSerialization.data(withJSONObject: object)
  34. return (data.count, {
  35. try $0.write(data)
  36. })
  37. case .text(let body):
  38. let data = [UInt8](body.utf8)
  39. return (data.count, {
  40. try $0.write(data)
  41. })
  42. case .html(let html):
  43. let data = [UInt8](html.utf8)
  44. return (data.count, {
  45. try $0.write(data)
  46. })
  47. case .htmlBody(let body):
  48. let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
  49. let data = [UInt8](serialised.utf8)
  50. return (data.count, {
  51. try $0.write(data)
  52. })
  53. case .data(let data, _):
  54. return (data.count, {
  55. try $0.write(data)
  56. })
  57. case .custom(let object, let closure):
  58. let serialised = try closure(object)
  59. let data = [UInt8](serialised.utf8)
  60. return (data.count, {
  61. try $0.write(data)
  62. })
  63. }
  64. } catch {
  65. let data = [UInt8]("Serialisation error: \(error)".utf8)
  66. return (data.count, {
  67. try $0.write(data)
  68. })
  69. }
  70. }
  71. }
  72. // swiftlint:disable cyclomatic_complexity
  73. public enum HttpResponse {
  74. case switchProtocols([String: String], (Socket) -> Void)
  75. case ok(HttpResponseBody), created, accepted
  76. case movedPermanently(String)
  77. case movedTemporarily(String)
  78. case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound, notAcceptable
  79. case tooManyRequests
  80. case internalServerError
  81. case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) throws -> Void)? )
  82. public var statusCode: Int {
  83. switch self {
  84. case .switchProtocols : return 101
  85. case .ok : return 200
  86. case .created : return 201
  87. case .accepted : return 202
  88. case .movedPermanently : return 301
  89. case .movedTemporarily : return 307
  90. case .badRequest : return 400
  91. case .unauthorized : return 401
  92. case .forbidden : return 403
  93. case .notFound : return 404
  94. case .notAcceptable : return 406
  95. case .tooManyRequests : return 429
  96. case .internalServerError : return 500
  97. case .raw(let code, _, _, _) : return code
  98. }
  99. }
  100. public var reasonPhrase: String {
  101. switch self {
  102. case .switchProtocols : return "Switching Protocols"
  103. case .ok : return "OK"
  104. case .created : return "Created"
  105. case .accepted : return "Accepted"
  106. case .movedPermanently : return "Moved Permanently"
  107. case .movedTemporarily : return "Moved Temporarily"
  108. case .badRequest : return "Bad Request"
  109. case .unauthorized : return "Unauthorized"
  110. case .forbidden : return "Forbidden"
  111. case .notFound : return "Not Found"
  112. case .notAcceptable : return "Not Acceptable"
  113. case .tooManyRequests : return "Too Many Requests"
  114. case .internalServerError : return "Internal Server Error"
  115. case .raw(_, let phrase, _, _) : return phrase
  116. }
  117. }
  118. public func headers() -> [String: String] {
  119. var headers = ["Server": "Swifter \(HttpServer.VERSION)"]
  120. switch self {
  121. case .switchProtocols(let switchHeaders, _):
  122. for (key, value) in switchHeaders {
  123. headers[key] = value
  124. }
  125. case .ok(let body):
  126. switch body {
  127. case .json: headers["Content-Type"] = "application/json"
  128. case .html: headers["Content-Type"] = "text/html"
  129. case .data(_, let contentType): headers["Content-Type"] = contentType
  130. default:break
  131. }
  132. case .movedPermanently(let location):
  133. headers["Location"] = location
  134. case .movedTemporarily(let location):
  135. headers["Location"] = location
  136. case .raw(_, _, let rawHeaders, _):
  137. if let rawHeaders = rawHeaders {
  138. for (key, value) in rawHeaders {
  139. headers.updateValue(value, forKey: key)
  140. }
  141. }
  142. default:break
  143. }
  144. return headers
  145. }
  146. func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) {
  147. switch self {
  148. case .ok(let body) : return body.content()
  149. case .badRequest(let body) : return body?.content() ?? (-1, nil)
  150. case .raw(_, _, _, let writer) : return (-1, writer)
  151. default : return (-1, nil)
  152. }
  153. }
  154. func socketSession() -> ((Socket) -> Void)? {
  155. switch self {
  156. case .switchProtocols(_, let handler) : return handler
  157. default: return nil
  158. }
  159. }
  160. }
  161. /**
  162. Makes it possible to compare handler responses with '==', but
  163. ignores any associated values. This should generally be what
  164. you want. E.g.:
  165. let resp = handler(updatedRequest)
  166. if resp == .NotFound {
  167. print("Client requested not found: \(request.url)")
  168. }
  169. */
  170. func == (inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
  171. return inLeft.statusCode == inRight.statusCode
  172. }