Created
December 11, 2018 15:12
-
-
Save nacho4d/d5e218e524e02037f4276b7bf39644d2 to your computer and use it in GitHub Desktop.
extension to print an NSURLRequest as a curl command (ready to be copy and pasted onto terminal, etc)
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
extension URLRequest { | |
/// Internal helper function to escape double quotes | |
func curlEscapeQuotes(in string: String) -> String { | |
return string.replacingOccurrences(of: "\"", with: "\\\"") | |
} | |
/// Curl Command string | |
var curlCommand: String { | |
guard let url = url else { | |
return "# No URL found" | |
} | |
var curlString = "curl -k -X \(httpMethod ?? "NULL") --dump-header -" | |
for header in (allHTTPHeaderFields ?? [:]) { | |
let headerKey = curlEscapeQuotes(in: header.key) | |
let headerValue = curlEscapeQuotes(in: header.value) | |
curlString += " -H \"\(headerKey): \(headerValue)\"" | |
} | |
if let httpBody = httpBody, | |
let bodyDataString = String(data: httpBody, encoding: .utf8), | |
!bodyDataString.isEmpty { | |
curlString += " -d \"\(bodyDataString)\"" | |
} | |
curlString += " \"\(url.absoluteString)\"" | |
return curlString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment