Created
January 21, 2020 23:03
-
-
Save maxchuquimia/1937a33912b36e2ec9daf18e497fe640 to your computer and use it in GitHub Desktop.
Represent URLRequest as a CURL string for easy debugging
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 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