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. #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. }
  21. public enum HttpResponseBody {
  22. case Json(AnyObject)
  23. case Html(String)
  24. case Text(String)
  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. #if os(Linux)
  31. let data = [UInt8]("Not ready for Linux.".utf8)
  32. return (data.count, {
  33. try $0.write(data)
  34. })
  35. #else
  36. guard NSJSONSerialization.isValidJSONObject(object) else {
  37. throw SerializationError.InvalidObject
  38. }
  39. let json = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted)
  40. let data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
  41. return (data.count, {
  42. try $0.write(data)
  43. })
  44. #endif
  45. case .Text(let body):
  46. let data = [UInt8](body.utf8)
  47. return (data.count, {
  48. try $0.write(data)
  49. })
  50. case .Html(let body):
  51. let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
  52. let data = [UInt8](serialised.utf8)
  53. return (data.count, {
  54. try $0.write(data)
  55. })
  56. case .Custom(let object, let closure):
  57. let serialised = try closure(object)
  58. let data = [UInt8](serialised.utf8)
  59. return (data.count, {
  60. try $0.write(data)
  61. })
  62. }
  63. } catch {
  64. let data = [UInt8]("Serialisation error: \(error)".utf8)
  65. return (data.count, {
  66. try $0.write(data)
  67. })
  68. }
  69. }
  70. }
  71. public enum HttpResponse {
  72. case SwitchProtocols([String: String], Socket -> Void)
  73. case OK(HttpResponseBody), Created, Accepted
  74. case MovedPermanently(String)
  75. case BadRequest(HttpResponseBody?), Unauthorized, Forbidden, NotFound
  76. case InternalServerError
  77. case RAW(Int, String, [String:String]?, (HttpResponseBodyWriter throws -> Void)? )
  78. func statusCode() -> Int {
  79. switch self {
  80. case .SwitchProtocols(_, _) : return 101
  81. case .OK(_) : return 200
  82. case .Created : return 201
  83. case .Accepted : return 202
  84. case .MovedPermanently : return 301
  85. case .BadRequest(_) : return 400
  86. case .Unauthorized : return 401
  87. case .Forbidden : return 403
  88. case .NotFound : return 404
  89. case .InternalServerError : return 500
  90. case .RAW(let code, _ , _, _) : return code
  91. }
  92. }
  93. func reasonPhrase() -> String {
  94. switch self {
  95. case .SwitchProtocols(_, _) : return "Switching Protocols"
  96. case .OK(_) : return "OK"
  97. case .Created : return "Created"
  98. case .Accepted : return "Accepted"
  99. case .MovedPermanently : return "Moved Permanently"
  100. case .BadRequest(_) : return "Bad Request"
  101. case .Unauthorized : return "Unauthorized"
  102. case .Forbidden : return "Forbidden"
  103. case .NotFound : return "Not Found"
  104. case .InternalServerError : return "Internal Server Error"
  105. case .RAW(_, let phrase, _, _) : return phrase
  106. }
  107. }
  108. func headers() -> [String: String] {
  109. var headers = ["Server" : "Swifter \(HttpServer.VERSION)"]
  110. switch self {
  111. case .SwitchProtocols(let switchHeaders, _):
  112. for (key, value) in switchHeaders {
  113. headers[key] = value
  114. }
  115. case .OK(let body):
  116. switch body {
  117. case .Json(_) : headers["Content-Type"] = "application/json"
  118. case .Html(_) : headers["Content-Type"] = "text/html"
  119. default:break
  120. }
  121. case .MovedPermanently(let location):
  122. headers["Location"] = location
  123. case .RAW(_, _, let rawHeaders, _):
  124. if let rawHeaders = rawHeaders {
  125. for (k, v) in rawHeaders {
  126. headers.updateValue(v, forKey: k)
  127. }
  128. }
  129. default:break
  130. }
  131. return headers
  132. }
  133. func content() -> (length: Int, write: (HttpResponseBodyWriter throws -> Void)?) {
  134. switch self {
  135. case .OK(let body) : return body.content()
  136. case .BadRequest(let body) : return body?.content() ?? (-1, nil)
  137. case .RAW(_, _, _, let writer) : return (-1, writer)
  138. default : return (-1, nil)
  139. }
  140. }
  141. func socketSession() -> (Socket -> Void)? {
  142. switch self {
  143. case SwitchProtocols(_, let handler) : return handler
  144. default: return nil
  145. }
  146. }
  147. }
  148. /**
  149. Makes it possible to compare handler responses with '==', but
  150. ignores any associated values. This should generally be what
  151. you want. E.g.:
  152. let resp = handler(updatedRequest)
  153. if resp == .NotFound {
  154. print("Client requested not found: \(request.url)")
  155. }
  156. */
  157. func ==(inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
  158. return inLeft.statusCode() == inRight.statusCode()
  159. }