-
-
Save khanlou/808d0c9937414147c3a70cbcd13e1e67 to your computer and use it in GitHub Desktop.
Print NSURLRequest in cURL format
This file contains hidden or 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
// | |
// URLRequest.swift | |
// | |
// Created by Peter Prokop on 17/08/2017. | |
// Modified by Soroush Khanlou on 09/12/2018. | |
import Foundation | |
public extension URLRequest { | |
/// Returns a cURL command for a request | |
/// - return A String object that contains cURL command or "" if an URL is not properly initalized. | |
public var cURLRepresentation: String { | |
guard | |
let url = url, | |
let httpMethod = httpMethod, | |
url.absoluteString.count > 0 | |
else { | |
return "" | |
} | |
var curlCommand = "curl --verbose \\\n" | |
curlCommand.append(" '\(url.absoluteString)' \\\n") | |
if httpMethod != "GET" { | |
curlCommand.append(" -X \(httpMethod) \\\n") | |
} | |
for (key, value) in allHTTPHeaderFields?.sorted(by: { $0.key < $1.key }) ?? [] { | |
curlCommand.append(" -H '\(key): \(self.value(forHTTPHeaderField: key)!)' \\\n") | |
} | |
if let httpBody = httpBody, | |
httpBody.count > 0, | |
let httpBodyString = String(data: httpBody, encoding: .utf8) { | |
let escapedHttpBody = httpBodyString.replacingOccurrences(of: "'", with: "'\\''") | |
curlCommand.append(" --data '\(escapedHttpBody)' \\\n") | |
} | |
return curlCommand | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment