Skip to content

Instantly share code, notes, and snippets.

@maxchuquimia
Created January 21, 2020 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxchuquimia/1937a33912b36e2ec9daf18e497fe640 to your computer and use it in GitHub Desktop.
Save maxchuquimia/1937a33912b36e2ec9daf18e497fe640 to your computer and use it in GitHub Desktop.
Represent URLRequest as a CURL string for easy debugging
extension URLRequest {
func curlString() -> String {
var curl = "curl --insecure"
// Method
if let method = httpMethod {
curl += " -X \(method)"
}
// Headers
for (name, val) in allHTTPHeaderFields ?? [:] {
curl += " -H '\(name): \(val)'"
}
// Body
if let body = httpBody {
// Should work in most cases
if let string = String(data: body, encoding: .utf8)?.replacingOccurrences(of: "'", with: "\\'") {
curl += " --data-binary '\(string)'"
} else {
curl += " --data-binary 'ERR_NOT_A_STRING'"
}
}
// URL
if let url = url?.absoluteString {
curl += " \(url)"
} else {
curl += " ERR_NO_URL"
}
return curl
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment