Skip to content

Instantly share code, notes, and snippets.

@khanlou
Forked from peterprokop/URLRequest.swift
Last active February 9, 2019 20:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/808d0c9937414147c3a70cbcd13e1e67 to your computer and use it in GitHub Desktop.
Save khanlou/808d0c9937414147c3a70cbcd13e1e67 to your computer and use it in GitHub Desktop.
Print NSURLRequest in cURL format
//
// URLRequest.swift
//
// Created by Peter Prokop on 17/08/2017.
// Modified by Soroush Khanlou on 09/12/2018.
import Foundation
public extension URLRequest {
/// Returns a cURL command for a request
/// - return A String object that contains cURL command or "" if an URL is not properly initalized.
public var cURLRepresentation: String {
guard
let url = url,
let httpMethod = httpMethod,
url.absoluteString.count > 0
else {
return ""
}
var curlCommand = "curl --verbose \\\n"
curlCommand.append(" '\(url.absoluteString)' \\\n")
if httpMethod != "GET" {
curlCommand.append(" -X \(httpMethod) \\\n")
}
for (key, value) in allHTTPHeaderFields?.sorted(by: { $0.key < $1.key }) ?? [] {
curlCommand.append(" -H '\(key): \(self.value(forHTTPHeaderField: key)!)' \\\n")
}
if let httpBody = httpBody,
httpBody.count > 0,
let httpBodyString = String(data: httpBody, encoding: .utf8) {
let escapedHttpBody = httpBodyString.replacingOccurrences(of: "'", with: "'\\''")
curlCommand.append(" --data '\(escapedHttpBody)' \\\n")
}
return curlCommand
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment