1
0

HttpResponse.swift 5.9 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: ErrorType {
  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. }
  22. public enum HttpResponseBody {
  23. case Json(AnyObject)
  24. case Html(String)
  25. case Text(String)
  26. case Custom(Any, (Any) throws -> String)
  27. func content() -> (Int, (HttpResponseBodyWriter throws -> Void)?) {
  28. do {
  29. switch self {
  30. case .Json(let object):
  31. #if os(Linux)
  32. let data = [UInt8]("Not ready for Linux.".utf8)
  33. return (data.count, {
  34. try $0.write(data)
  35. })
  36. #else
  37. guard NSJSONSerialization.isValidJSONObject(object) else {
  38. throw SerializationError.InvalidObject
  39. }
  40. let json = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted)
  41. let data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
  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. }