Skip to content

Instantly share code, notes, and snippets.

@fethica
Created October 20, 2018 02:08
Show Gist options
  • Save fethica/076f6504fecd8d91c031f385f63ea985 to your computer and use it in GitHub Desktop.
Save fethica/076f6504fecd8d91c031f385f63ea985 to your computer and use it in GitHub Desktop.
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