Skip to content

Instantly share code, notes, and snippets.

@d4rkd3v1l
Created October 27, 2021 13:03
Show Gist options
  • Save d4rkd3v1l/3b2858e9891763cc05ca3f6626b555ac to your computer and use it in GitHub Desktop.
Save d4rkd3v1l/3b2858e9891763cc05ca3f6626b555ac to your computer and use it in GitHub Desktop.
Print URLRequests as "raw" Strings in Swift
extension URLRequest {
/// Prints the request as "raw" String
///
/// Like:
/// ```
/// GET /path HTTP/1.1
/// Host: host
/// Header: Value
/// Header: Value
///
/// { "some": "body", "for PUT requests": "or POST requests" }
/// ```
var raw: String {
"""
\(self.httpMethod ?? "") \(self.url?.relativePath ?? "")\(self.url?.query == nil ? "" : "?")\(self.url?.query ?? "") HTTP/1.1
Host: \(self.url?.scheme ?? "")://\(self.url?.host ?? "")
\((self.allHTTPHeaderFields?.compactMap { "\($0): \($1)" } ?? []).joined(separator: "\n"))
\(String(data: self.httpBody ?? Data(), encoding: .utf8) ?? "")
"""
}
}
@d4rkd3v1l
Copy link
Author

Not that nice code, but does the trick so far. 😎

Just use po request.raw as NSString in Xcode, or just do whatever you want with it^^ 🤷‍♂️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment