Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Last active April 17, 2020 13:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dedeexe/de73bfc0a164ff3d4a40949d6b508f11 to your computer and use it in GitHub Desktop.
Save dedeexe/de73bfc0a164ff3d4a40949d6b508f11 to your computer and use it in GitHub Desktop.
Convert URL Request to curl command
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