Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Created December 11, 2018 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nacho4d/d5e218e524e02037f4276b7bf39644d2 to your computer and use it in GitHub Desktop.
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)
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