1
0

HttpResponse.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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
  79. case internalServerError
  80. case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) throws -> Void)? )
  81. public var statusCode: Int {
  82. switch self {
  83. case .switchProtocols : return 101
  84. case .ok : return 200
  85. case .created : return 201
  86. case .accepted : return 202
  87. case .movedPermanently : return 301
  88. case .movedTemporarily : return 307
  89. case .badRequest : return 400
  90. case .unauthorized : return 401
  91. case .forbidden : return 403
  92. case .notFound : return 404
  93. case .internalServerError : return 500
  94. case .raw(let code, _, _, _) : return code
  95. }
  96. }
  97. public var reasonPhrase: String {
  98. switch self {
  99. case .switchProtocols : return "Switching Protocols"
  100. case .ok : return "OK"
  101. case .created : return "Created"
  102. case .accepted : return "Accepted"
  103. case .movedPermanently : return "Moved Permanently"
  104. case .movedTemporarily : return "Moved Temporarily"
  105. case .badRequest : return "Bad Request"
  106. case .unauthorized : return "Unauthorized"
  107. case .forbidden : return "Forbidden"
  108. case .notFound : return "Not Found"
  109. case .internalServerError : return "Internal Server Error"
  110. case .raw(_, let phrase, _, _) : return phrase
  111. }
  112. }
  113. public func headers() -> [String: String] {
  114. var headers = ["Server": "Swifter \(HttpServer.VERSION)"]
  115. switch self {
  116. case .switchProtocols(let switchHeaders, _):
  117. for (key, value) in switchHeaders {
  118. headers[key] = value
  119. }
  120. case .ok(let body):
  121. switch body {
  122. case .json: headers["Content-Type"] = "application/json"
  123. case .html: headers["Content-Type"] = "text/html"
  124. case .data(_, let contentType): headers["Content-Type"] = contentType
  125. default:break
  126. }
  127. case .movedPermanently(let location):
  128. headers["Location"] = location
  129. case .movedTemporarily(let location):
  130. headers["Location"] = location
  131. case .raw(_, _, let rawHeaders, _):
  132. if let rawHeaders = rawHeaders {
  133. for (key, value) in rawHeaders {
  134. headers.updateValue(value, forKey: key)
  135. }
  136. }
  137. default:break
  138. }
  139. return headers
  140. }
  141. func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) {
  142. switch self {
  143. case .ok(let body) : return body.content()
  144. case .badRequest(let body) : return body?.content() ?? (-1, nil)
  145. case .raw(_, _, _, let writer) : return (-1, writer)
  146. default : return (-1, nil)
  147. }
  148. }
  149. func socketSession() -> ((Socket) -> Void)? {
  150. switch self {
  151. case .switchProtocols(_, let handler) : return handler
  152. default: return nil
  153. }
  154. }
  155. }
  156. /**
  157. Makes it possible to compare handler responses with '==', but
  158. ignores any associated values. This should generally be what
  159. you want. E.g.:
  160. let resp = handler(updatedRequest)
  161. if resp == .NotFound {
  162. print("Client requested not found: \(request.url)")
  163. }
  164. */
  165. func == (inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
  166. return inLeft.statusCode == inRight.statusCode
  167. }