MCPcopy Create free account
hub / github.com/azadkuh/qhttp / Server

Class Server

example/keep-alive/main.cpp:112–163  ·  view source on GitHub ↗

//////////////////////////////////////////////////////////////////////////

Source from the content-addressed store, hash-verified

110using namespace qhttp::server;
111///////////////////////////////////////////////////////////////////////////////
112struct Server : public QHttpServer
113{
114 using QHttpServer::QHttpServer;
115
116 int start(quint16 port) {
117 connect(this, &QHttpServer::newConnection, [this](QHttpConnection*){
118 printf("a new connection has been come!\n");
119 });
120
121 bool isListening = listen(
122 QString::number(port),
123 [this](QHttpRequest* req, QHttpResponse* res){
124 req->collectData(512);
125 req->onEnd([this, req, res](){
126 process(req, res);
127 });
128 });
129
130 if ( !isListening ) {
131 qDebug("can not listen on %d!\n", port);
132 return -1;
133 }
134
135 return qApp->exec();
136 }
137
138 void process(QHttpRequest* req, QHttpResponse* res) {
139 auto root = QJsonDocument::fromJson(req->collectedData()).object();
140
141 if ( root.isEmpty() || root.value("name").toString() != QLatin1Literal("add") ) {
142 const static char KMessage[] = "Invalid json format!";
143 res->setStatusCode(qhttp::ESTATUS_BAD_REQUEST);
144 res->addHeader("connection", "close");
145 res->addHeaderValue("content-length", strlen(KMessage));
146 res->end(KMessage);
147 return;
148 }
149
150 int total = 0;
151 auto args = root.value("args").toArray();
152 for ( const auto jv : args ) {
153 total += jv.toInt();
154 }
155 root["args"] = total;
156
157 QByteArray body = QJsonDocument(root).toJson();
158 res->addHeader("connection", "keep-alive");
159 res->addHeaderValue("content-length", body.length());
160 res->setStatusCode(qhttp::ESTATUS_OK);
161 res->end(body);
162 }
163}; // struct server
164///////////////////////////////////////////////////////////////////////////////
165} // namespace server
166///////////////////////////////////////////////////////////////////////////////

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected