Last active
July 22, 2018 14:19
-
-
Save palmin/7211c18a1a862d61bd5e620ef5a9d166 to your computer and use it in GitHub Desktop.
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 { | |
private func quote(_ string: String) -> String { | |
// handle all the regular escape sequences | |
var text = string.replacingOccurrences(of: "\\", with: "\\\\") | |
text = text.replacingOccurrences(of: "\"", with: "\\\"") | |
text = text.replacingOccurrences(of: "\n", with: "\\\n") | |
text = text.replacingOccurrences(of: "\r", with: "\\\r") | |
text = text.replacingOccurrences(of: "\t", with: "\\\t") | |
return "\"\(text)\"" | |
} | |
public func asCurlCommand() -> String { | |
guard let url = self.url else { | |
return "echo 'Unable to determine url from URLRequest'" | |
} | |
var headers = "" | |
for (key,val) in self.allHTTPHeaderFields ?? [:] { | |
let header = "\(key): \(val)" | |
headers += "-H \(quote(header)) " | |
} | |
var data = "" | |
if let body = self.httpBody { | |
guard let string = String(data: body, encoding: .utf8) else { | |
return "echo 'Unable to represent httpBody as UTF8 string'" | |
} | |
data = "--data \(quote(string)) " | |
} | |
var X = "" | |
if let method = self.httpMethod { | |
X = "-X \(quote(method)) " | |
} | |
return "curl -v \(X)\(headers)\(data)\(quote(url.absoluteString))" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment