Last active
April 17, 2020 13:08
-
-
Save dedeexe/de73bfc0a164ff3d4a40949d6b508f11 to your computer and use it in GitHub Desktop.
Convert URL Request 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 { | |
public func curl(pretty:Bool = false) -> String { | |
var data : String = "" | |
let complement = pretty ? "\\\n" : "" | |
let method = "-X \(self.httpMethod ?? "GET") \(complement)" | |
let url = "\"" + self.url?.absoluteString ?? "" + "\"" | |
var header = "" | |
if let httpHeaders = self.allHTTPHeaderFields, httpHeaders.keys.count > 0 { | |
for (key,value) in httpHeaders { | |
header += "-H \"\(key): \(value)\" \(complement)" | |
} | |
} | |
if let bodyData = self.httpBody, let bodyString = String(data:bodyData, encoding:.utf8) { | |
data = "-d \"\(bodyString)\" \(complement)" | |
} | |
let command = "curl -i " + complement + method + header + data + url | |
return command | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment