Created
October 27, 2021 13:03
-
-
Save d4rkd3v1l/3b2858e9891763cc05ca3f6626b555ac to your computer and use it in GitHub Desktop.
Print URLRequests as "raw" Strings in Swift
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 { | |
/// 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) ?? "") | |
""" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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^^ 🤷♂️