JSON-RPC 2.0
JSON-RPC 2.0 Modern C++ Library
Loading...
Searching...
No Matches
framed_transport.cpp
Go to the documentation of this file.
2
3#include <stdexcept>
4
6
7namespace jsonrpc::transport {
8
10 std::ostream &output, const std::string &message) {
11 output << "Content-Length: " << message.size() << "\r\n"
12 << "Content-Type: application/vscode-jsonrpc; charset=utf-8\r\n"
13 << "\r\n"
14 << message;
15}
16
18 -> FramedTransport::HeaderMap {
19 HeaderMap headers;
20 std::string line;
21
22 while (std::getline(input, line) && !line.empty() && line != "\r") {
23 auto colon_pos = line.find(':');
24 if (colon_pos != std::string::npos) {
25 std::string header_key = utils::Trim(line.substr(0, colon_pos));
26 std::string header_value = utils::Trim(line.substr(colon_pos + 1));
27 headers[header_key] = header_value;
28 }
29 }
30
31 if (headers.empty()) {
32 throw std::runtime_error("Failed to read headers");
33 }
34
35 return headers;
36}
37
38auto FramedTransport::ReadContentLengthFromStream(std::istream &input) -> int {
39 auto headers = ReadHeadersFromStream(input);
40 auto it = headers.find("Content-Length");
41 if (it == headers.end()) {
42 throw std::runtime_error("Content-Length header missing");
43 }
44 return ParseContentLength(it->second);
45}
46
48 std::istream &input, std::size_t content_length) -> std::string {
49 std::string content(content_length, '\0');
50 input.read(content.data(), static_cast<std::streamsize>(content_length));
51 if (input.gcount() != static_cast<std::streamsize>(content_length)) {
52 throw std::runtime_error("Failed to read the expected content length");
53 }
54 return content;
55}
56
57auto FramedTransport::ReceiveFramedMessage(std::istream &input) -> std::string {
58 int content_length = ReadContentLengthFromStream(input);
59 return ReadContent(input, content_length);
60}
61
62auto FramedTransport::ParseContentLength(const std::string &header_value)
63 -> int {
64 try {
65 return std::stoi(header_value);
66 } catch (const std::invalid_argument &) {
67 throw std::runtime_error("Invalid Content-Length value");
68 } catch (const std::out_of_range &) {
69 throw std::runtime_error("Content-Length value out of range");
70 }
71}
72
73} // namespace jsonrpc::transport
static auto ReadContentLengthFromStream(std::istream &input) -> int
static auto ReceiveFramedMessage(std::istream &input) -> std::string
Receives a framed message.
static auto ReadContent(std::istream &input, std::size_t content_length) -> std::string
Reads content from the input stream based on the content length.
static auto ReadHeadersFromStream(std::istream &input) -> HeaderMap
static void FrameMessage(std::ostream &output, const std::string &message)
Constructs a framed message.
auto Trim(std::string_view in) -> std::string