Last active
August 15, 2024 09:46
-
-
Save shaps80/ba6a1e2d477af0383e8f19b87f53661d to your computer and use it in GitHub Desktop.
Generates a cURL command representation of a URLRequest in Swift.
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
import Foundation | |
extension URLRequest { | |
/** | |
Returns a cURL command representation of this URL request. | |
*/ | |
public var curlString: String { | |
guard let url = url else { return "" } | |
var baseCommand = #"curl "\#(url.absoluteString)""# | |
if httpMethod == "HEAD" { | |
baseCommand += " --head" | |
} | |
var command = [baseCommand] | |
if let method = httpMethod, method != "GET" && method != "HEAD" { | |
command.append("-X \(method)") | |
} | |
if let headers = allHTTPHeaderFields { | |
for (key, value) in headers where key != "Cookie" { | |
command.append("-H '\(key): \(value)'") | |
} | |
} | |
if let data = httpBody, let body = String(data: data, encoding: .utf8) { | |
command.append("-d '\(body)'") | |
} | |
return command.joined(separator: " \\\n\t") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just post a gist based on gist that is a custom LLDB command that generates a cURL command from any URLRequest in Swift. Hope find it interesting! :)
https://gist.github.com/AlvaroOlave/2ddf2b1e99d4477a51146530b7801aa0