Forked from ollieatkinson/URLRequest+cURLCommand.swift
Created
March 2, 2017 21:19
-
-
Save eonist/55347474402bd1048a73cecff0088dcd to your computer and use it in GitHub Desktop.
Generate cURL command's from URLRequest's
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 { | |
/// The cURL representation of the URLRequest, useful for debugging and executing requests outside of the app. | |
var cURLCommand: String { | |
var command = "curl" | |
if let httpMethod = httpMethod { | |
command.append(commandLineArgument: "-X \(httpMethod)") | |
} | |
if let httpBody = httpBody, httpBody.count > 0 { | |
var bodyString = String(data: httpBody, encoding: .utf8) | |
[ ("\\", "\\\\"), ("`", "\\`"), ("\"", "\\\""), ("$", "\\$") ].forEach { search, replace in | |
bodyString = bodyString?.replacingOccurrences(of: search, with: replace) | |
} | |
command.append(commandLineArgument: "-d \"\(bodyString)\"") | |
} | |
if let acceptEncoderHeader = allHTTPHeaderFields?["Accept-Encoding"], (acceptEncoderHeader as NSString).range(of: "gzip").location != NSNotFound { | |
command.append(commandLineArgument: "--compressed") | |
} | |
if let url = url, let cookies = HTTPCookieStorage.shared.cookies(for: url), cookies.count > 0 { | |
let cookieCommand = cookies.map { | |
"\($0.name)=\($0.value);" | |
}.joined() | |
command.append(commandLineArgument: "--cookie \"\(cookieCommand)\"") | |
} | |
if let allHTTPHeaderFields = allHTTPHeaderFields { | |
for (header, value) in allHTTPHeaderFields { | |
command.append(commandLineArgument: "-H '\(header): \(value.replacingOccurrences(of: "\'", with: "\\\'"))'") | |
} | |
} | |
if let url = url { | |
command.append(commandLineArgument: "\"\(url.absoluteString)\"") | |
} | |
return command | |
} | |
} | |
fileprivate extension String { | |
mutating func append(commandLineArgument: String) { | |
append(" \(commandLineArgument.trimmingCharacters(in: CharacterSet.whitespaces))") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment