Skip to content

Instantly share code, notes, and snippets.

@buntylm
Created December 14, 2021 05:54
Show Gist options
  • Save buntylm/6efeb447c4ee2168faa24baba0a1e943 to your computer and use it in GitHub Desktop.
Save buntylm/6efeb447c4ee2168faa24baba0a1e943 to your computer and use it in GitHub Desktop.
Extension for `URLRequest` to get the CURL out of it.
import Foundation
extension URLRequest {
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