Skip to content

Commit

Permalink
send json with desired status code
Browse files Browse the repository at this point in the history
  • Loading branch information
abiaad committed Mar 6, 2016
1 parent b25adff commit f03067c
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions Sources/Response.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,21 +183,23 @@ extension Response {
send()
}

public func send(json json: Any) {

public func send(json json: Any, status: Status = .OK) {
let data: [UInt8]

if let json = json as? AnyObject {
if NSJSONSerialization.isValidJSONObject(json) {

do {
let json = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
} catch let errorMessage {
self.send(error: "Server error: \(errorMessage)")
return
}

do {
let json = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))
} catch let errorMessage {
self.status = .Error
self.send(error: "Server error: \(errorMessage)")
return
}
} else {
self.status = .Error
self.send(error: "Server error: Invalid JSON")
return
}
Expand All @@ -206,12 +208,11 @@ extension Response {
let string = JSONSerializer.serialize(json)
data = [UInt8](string.utf8)
}


self.status = status
contentType = .JSON
status = .OK
body = data

self.send()
}

Expand Down

0 comments on commit f03067c

Please sign in to comment.