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

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

WBOY
Release: 2024-05-31 22:42:59
Original
977 people have browsed it

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)
Copy after login

Create server

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

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>");
});
Copy after login

Send a response

response->Send();
Copy after login

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));
});
Copy after login

Running Server

server.Run();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template