Skip to content

Instantly share code, notes, and snippets.

@testillano
Last active June 30, 2022 00:10
Show Gist options
  • Save testillano/c25c770d3157fdfeecf4ef56cb198dfc to your computer and use it in GitHub Desktop.
Save testillano/c25c770d3157fdfeecf4ef56cb198dfc to your computer and use it in GitHub Desktop.
asio-sv3 simplified (without Queue for worker threads)
#include <iostream>
#include <string>
#include <mutex>
#include <thread>
#include <future>
#include <deque>
#include <nghttp2/asio_http2_server.h>
using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::server;
struct Stream : public std::enable_shared_from_this<Stream> {
Stream(const request &req, const response &res,
boost::asio::io_service &io_service)
: io_service(io_service), req(req), res(res), closed(false) {}
void commit_result() {
auto self = shared_from_this();
io_service.post([self]() {
std::lock_guard<std::mutex> lg(self->mu);
if (self->closed) {
return;
}
self->res.write_head(200);
self->res.end("done");
});
}
void set_closed(bool f) {
std::lock_guard<std::mutex> lg(mu);
closed = f;
}
boost::asio::io_service &io_service;
std::mutex mu;
const request &req;
const response &res;
bool closed;
};
int main(int argc, char **argv) {
http2 server;
server.num_threads(1);
server.handle("/", [](const request &req, const response &res) {
auto &io_service = res.io_service();
auto st = std::make_shared<Stream>(req, res, io_service);
res.on_close([st](uint32_t error_code) {
st->set_closed(true);
});
st->commit_result();
});
boost::system::error_code ec;
if (server.listen_and_serve(ec, "127.0.0.1", "3000")) {
std::cerr << "error: " << ec.message() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment