HttpResponse.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. //
  2. // HttpResponse.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. #if os(Linux)
  8. import Glibc
  9. #else
  10. import Foundation
  11. #endif
  12. public enum SerializationError: Error {
  13. case invalidObject
  14. case notSupported
  15. }
  16. public protocol HttpResponseBodyWriter {
  17. func write(_ file: File) throws
  18. func write(_ data: [UInt8]) throws
  19. func write(_ data: ArraySlice<UInt8>) throws
  20. func write(_ data: NSData) throws
  21. func write(_ data: Data) throws
  22. }
  23. public enum HttpResponseBody {
  24. case json(AnyObject)
  25. case html(String)
  26. case text(String)
  27. case custom(Any, (Any) throws -> String)
  28. func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
  29. do {
  30. switch self {
  31. case .json(let object):
  32. #if os(Linux)
  33. let data = [UInt8]("Not ready for Linux.".utf8)
  34. return (data.count, {
  35. try $0.write(data)
  36. })
  37. #else
  38. guard JSONSerialization.isValidJSONObject(object) else {
  39. throw SerializationError.invalidObject
  40. }
  41. let data = try JSONSerialization.data(withJSONObject: object)
  42. return (data.count, {
  43. try $0.write(data)
  44. })
  45. #endif
  46. case .text(let body):
  47. let data = [UInt8](body.utf8)
  48. return (data.count, {
  49. try $0.write(data)
  50. })
  51. case .html(let body):
  52. let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
  53. let data = [UInt8](serialised.utf8)
  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. public enum HttpResponse {
  73. case switchProtocols([String: String], (Socket) -> Void)
  74. case ok(HttpResponseBody), created, accepted
  75. case movedPermanently(String)
  76. case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound
  77. case internalServerError
  78. case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) throws -> Void)? )
  79. func statusCode() -> Int {
  80. switch self {
  81. case .switchProtocols(_, _) : return 101
  82. case .ok(_) : return 200
  83. case .created : return 201
  84. case .accepted : return 202
  85. case .movedPermanently : return 301
  86. case .badRequest(_) : return 400
  87. case .unauthorized : return 401
  88. case .forbidden : return 403
  89. case .notFound : return 404
  90. case .internalServerError : return 500
  91. case .raw(let code, _ , _, _) : return code
  92. }
  93. }
  94. func reasonPhrase() -> String {
  95. switch self {
  96. case .switchProtocols(_, _) : return "Switching Protocols"
  97. case .ok(_) : return "OK"
  98. case .created : return "Created"
  99. case .accepted : return "Accepted"
  100. case .movedPermanently : return "Moved Permanently"
  101. case .badRequest(_) : return "Bad Request"
  102. case .unauthorized : return "Unauthorized"
  103. case .forbidden : return "Forbidden"
  104. case .notFound : return "Not Found"
  105. case .internalServerError : return "Internal Server Error"
  106. case .raw(_, let phrase, _, _) : return phrase
  107. }
  108. }
  109. func headers() -> [String: String] {
  110. var headers = ["Server" : "Swifter \(HttpServer.VERSION)"]
  111. switch self {
  112. case .switchProtocols(let switchHeaders, _):
  113. for (key, value) in switchHeaders {
  114. headers[key] = value
  115. }
  116. case .ok(let body):
  117. switch body {
  118. case .json(_) : headers["Content-Type"] = "application/json"
  119. case .html(_) : headers["Content-Type"] = "text/html"
  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. }