Created
March 7, 2018 03:43
-
-
Save ming-chu/2520719533e096c8f69b188f82d64e73 to your computer and use it in GitHub Desktop.
Swift Convert URLRequest to curl command
This file contains 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
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