-
-
Save shaps80/ba6a1e2d477af0383e8f19b87f53661d to your computer and use it in GitHub Desktop.
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") | |
} | |
} |
Hi shaps80, can you hellp me more about curl in swift way?
Hi @shaps80
I added double quotes around url.absoluteString
, otherwise the curl command in terminal doesn't work correctly (especially if there are multiple query parameters).
so the line with baseCommand looks like:
>= swift 5:
var baseCommand = #"curl "\#(url.absoluteString)""#
Older versions of swift:
var baseCommand = "curl \"\(url.absoluteString)\""
Ali
This is super helpful! Thanks.
No worries, glad you found it useful.
Thankyou this is helpful
Thankyou this is helpful
👊
Hi @shaps80
I added double quotes around
url.absoluteString
, otherwise the curl command in terminal doesn't work correctly (especially if there are multiple query parameters).
so the line with baseCommand looks like:>= swift 5:
var baseCommand = #"curl "\#(url.absoluteString)""#
Older versions of swift:
var baseCommand = "curl \"\(url.absoluteString)\""
Ali
👊
You can write as
#if swift(>=5.0)
var baseCommand = #"curl "\#(url.absoluteString)""#
#else
var baseCommand = "curl \"\(url.absoluteString)\""
#endif
it will check the swift version at compile time
You can write as
#if swift(>=5.0) var baseCommand = #"curl "\#(url.absoluteString)""# #else var baseCommand = "curl \"\(url.absoluteString)\"" #endifit will check the swift version at compile time
👊
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
@AlvaroOlave I love this! No need to include the code in every project! Amazing :)
Quick attribution: I wrote this implementation myself, but it was inspired from a few years back when I saw @dantoml implement this in a project we were working on. One of the most useful pieces of code and I use it almost every day.