HttpResponse.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. let data = [UInt8]("Not ready for Linux.".utf8)
  28. return (data.count, {
  29. $0.write(data)
  30. })
  31. #else
  32. guard JSONSerialization.isValidJSONObject(object) else {
  33. throw SerializationError.InvalidObject
  34. }
  35. let json = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
  36. return (json.count, {
  37. $0.write(json)
  38. })
  39. #endif
  40. case .Text(let body):
  41. let data = [UInt8](body.utf8)
  42. return (data.count, {
  43. $0.write(data)
  44. })
  45. case .Html(let body):
  46. let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
  47. let data = [UInt8](serialised.utf8)
  48. return (data.count, {
  49. $0.write(data)
  50. })
  51. case .Data(let body):
  52. return (body.count, {
  53. $0.write(body)
  54. })
  55. case .Custom(let object, let closure):
  56. let serialised = try closure(object)
  57. let data = [UInt8](serialised.utf8)
  58. return (data.count, {
  59. $0.write(data)
  60. })
  61. }
  62. } catch {
  63. let data = [UInt8]("Serialisation error: \(error)".utf8)
  64. return (data.count, {
  65. $0.write(data)
  66. })
  67. }
  68. }
  69. }
  70. public enum HttpResponse {
  71. case SwitchProtocols([String: String], (Socket) -> Void)
  72. case OK(HttpResponseBody), Created, Accepted
  73. case MovedPermanently(String)
  74. case BadRequest(HttpResponseBody?), Unauthorized, Forbidden, NotFound
  75. case InternalServerError
  76. case RAW(Int, String, [String:String]?, ((HttpResponseBodyWriter) -> Void)? )
  77. func statusCode() -> Int {
  78. switch self {
  79. case .SwitchProtocols(_, _) : return 101
  80. case .OK(_) : return 200
  81. case .Created : return 201
  82. case .Accepted : return 202
  83. case .MovedPermanently : return 301
  84. case .BadRequest(_) : return 400
  85. case .Unauthorized : return 401
  86. case .Forbidden : return 403
  87. case .NotFound : return 404
  88. case .InternalServerError : return 500
  89. case .RAW(let code, _ , _, _) : return code
  90. }
  91. }
  92. func reasonPhrase() -> String {
  93. switch self {
  94. case .SwitchProtocols(_, _) : return "Switching Protocols"
  95. case .OK(_) : return "OK"
  96. case .Created : return "Created"
  97. case .Accepted : return "Accepted"
  98. case .MovedPermanently : return "Moved Permanently"
  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. 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 .Text(_) : headers["Content-Type"] = "text/plain"
  117. case .Json(_) : headers["Content-Type"] = "application/json"
  118. case .Html(_) : headers["Content-Type"] = "text/html"
  119. case .Data(_) : headers["Content-Type"] = "application/octet-stream"
  120. default:break
  121. }
  122. case .MovedPermanently(let location):
  123. headers["Location"] = location
  124. case .RAW(_, _, let rawHeaders, _):
  125. if let rawHeaders = rawHeaders {
  126. for (k, v) in rawHeaders {
  127. headers.updateValue(v, forKey: k)
  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. }