Created
October 20, 2018 02:08
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension URLRequest { | |
static func record(_ request:URLRequest, _ response:URLResponse?, _ data:Data?, _ error:Error?) { | |
#if DEBUG | |
print("\n🔵 REQUEST:\n" + request.debugDescription) | |
if let data = data, | |
let response = String(data: data, encoding: .utf8) { | |
print("\n✅ RESPONSE:\n\(response)" + "\n") | |
} else { | |
print("\n❌ ERROR:\n" + (error?.localizedDescription ?? "unknown error") + "\n") | |
} | |
#endif | |
} | |
private var debugDescription: String { | |
return cURLRepresentation() | |
} | |
private func cURLRepresentation() -> String { | |
guard let url = self.url else { return "$ curl command could not be created" } | |
var components = ["curl -v"] | |
if let httpMethod = httpMethod, httpMethod != "GET" { | |
components.append("-X \(httpMethod)") | |
} | |
var headers: [AnyHashable: Any] = [:] | |
if let headerFields = allHTTPHeaderFields { | |
for (field, value) in headerFields where field != "Cookie" { | |
headers[field] = value | |
} | |
} | |
for (field, value) in headers { | |
components.append("-H \"\(field): \(value)\"") | |
} | |
if let httpBodyData = self.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { | |
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") | |
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") | |
components.append("-d \"\(escapedBody)\"") | |
} | |
components.append("\"\(url.absoluteString)\"") | |
return components.joined(separator: " \\\n\t") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment