Home  >  Article  >  Backend Development  >  How to handle web requests and responses in C++?

How to handle web requests and responses in C++?

WBOY
WBOYOriginal
2024-05-31 22:42:59964browse

The steps to use the cpproxy library to handle web requests and responses are as follows: Install the cpproxy library. Create an HTTP server object and set the port and address. Set handlers for specific request paths. In the handler, create the response object, set the status code and header information, and write the response content. Send response. Run the server.

How to handle web requests and responses in C++?

How to handle web requests and responses in C

When handling web requests and responses in C, you can use something called HTTP server library. This article will guide you through doing this using the popular cpproxy library.

Installation

Use a package manager (e.g. CMake):

find_package(cpproxy REQUIRED)

Create server

cpproxy::WebSocketServer server;
server.set_port(80);
server.set_address("127.0.0.1");

Handling requests

Set a handler for a specific request path:

server.HandleRequest("/", [](cpproxy::Requester* request) {
  cpproxy::Response* response = new cpproxy::Response(request);
  response->SetStatusCode(200);
  response->SetHeader("Content-Type", "text/html");
  response->Write("<html><body>Hello World!</body></html>");
});

Send a response

response->Send();

Actual case: Simple Calculator

server.HandleRequest("/calc", [](cpproxy::Requester* request) {
  int a = std::stoi(request->GetParameter("a"));
  int b = std::stoi(request->GetParameter("b"));
  int result = a + b;

  cpproxy::Response* response = new cpproxy::Response(request);
  response->SetStatusCode(200);
  response->SetHeader("Content-Type", "text/plain");
  response->Write(std::to_string(result));
});

Running Server

server.Run();

The above is the detailed content of How to handle web requests and responses in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn