Skip to content

Instantly share code, notes, and snippets.

@ming-chu
Created March 7, 2018 03:43
Show Gist options
  • Save ming-chu/2520719533e096c8f69b188f82d64e73 to your computer and use it in GitHub Desktop.
Save ming-chu/2520719533e096c8f69b188f82d64e73 to your computer and use it in GitHub Desktop.
Swift Convert URLRequest to curl command
extension URLRequest {
func toCurlCommand() -> String {
func escapeTerminalString(_ value: String) -> String {
return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil)
}
let method = self.httpMethod ?? "GET"
var returnValue = "curl -i \n -X \(method) "
for (key, value) in self.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString(key)
let escapedValue = escapeTerminalString(value)
returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" "
}
if let httpBody = self.httpBody, self.httpMethod == "POST" {
let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8)
if let body = maybeBody {
returnValue += "\n -d \"\(escapeTerminalString(body))\" "
}
}
let URLString = self.url?.absoluteString ?? "<unknown url>"
returnValue += "\n \"\(escapeTerminalString(URLString))\""
return returnValue.replacingOccurrences(of: "\n", with: "\\\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment