Last active
July 16, 2025 14:07
-
-
Save thomsmed/37e84842bbd46d566c837f4600a067f7 to your computer and use it in GitHub Desktop.
A simple URLRequest extension that map the request to curl representation.
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 | |
public extension URLRequest { | |
var curlRepresentation: String { | |
guard let url = url?.absoluteString else { | |
return "could not create curl command" | |
} | |
var components = ["curl \(url)"] | |
if let method = httpMethod, method != "GET" { | |
components.append("-X \(method)") | |
} | |
for (key, value) in allHTTPHeaderFields ?? [:] { | |
components.append("-H '\(key): \(value)'") | |
} | |
if let body = httpBody, let bodyString = String(data: body, encoding: .utf8) { | |
let sanitizedBody = bodyString | |
.replacingOccurrences(of: "\\", with: "\\\\") | |
.replacingOccurrences(of: "'", with: "\\'") | |
components.append("-d '\(sanitizedBody)'") | |
} | |
return components.joined(separator: " \\\n\t") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment