1
0

HttpResponse.swift 5.9 KB

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