Convert Figma logo to code with AI

facebook logoproxygen

A collection of C++ HTTP libraries including an easy to use HTTP server.

8,116
1,486
8,116
26

Top Related Projects

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

http request/response parser for c

A C++ header-only HTTP/HTTPS server and client library

Simple, secure & standards compliant web server for the most demanding of applications

A curated list of awesome C++ (or C) frameworks, libraries, resources, and shiny things. Inspired by awesome-... stuff.

An HTML5 parsing library in pure C99

Quick Overview

Proxygen is a collection of C++ HTTP libraries, including an easy-to-use HTTP server. Developed and maintained by Facebook, it's designed to be fast, efficient, and flexible, making it suitable for high-performance web applications and services.

Pros

  • High performance and scalability, optimized for modern hardware
  • Extensive feature set, including HTTP/1.1, HTTP/2, and QUIC support
  • Well-documented and actively maintained by Facebook
  • Modular design allowing for easy customization and extension

Cons

  • Steep learning curve for developers not familiar with C++ or advanced networking concepts
  • Limited cross-platform support, primarily focused on Linux
  • Requires significant system resources compared to lighter alternatives
  • Complexity may be overkill for simple web applications

Code Examples

  1. Creating a simple HTTP server:
#include <proxygen/httpserver/HTTPServer.h>
#include <proxygen/httpserver/RequestHandlerFactory.h>

class HelloHandler : public proxygen::RequestHandler {
 public:
  void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept override {
    // Request handling logic
  }

  void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override {
    // Request body handling
  }

  void onEOM() noexcept override {
    ResponseBuilder(downstream_)
      .status(200, "OK")
      .body("Hello, World!")
      .sendWithEOM();
  }
};

int main() {
  proxygen::HTTPServerOptions options;
  options.threads = 0;
  options.idleTimeout = std::chrono::milliseconds(60000);
  options.shutdownOn = {SIGINT, SIGTERM};
  options.enableContentCompression = false;
  options.handlerFactories = proxygen::RequestHandlerChain()
    .addThen<HelloHandlerFactory>()
    .build();

  proxygen::HTTPServer server(std::move(options));
  server.bind({"localhost", 8080});
  server.start();
  server.waitForStop();

  return 0;
}
  1. Handling POST requests:
void HelloHandler::onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept {
  if (headers->getMethod() == proxygen::HTTPMethod::POST) {
    // Handle POST request
  } else {
    // Handle other methods
  }
}

void HelloHandler::onBody(std::unique_ptr<folly::IOBuf> body) noexcept {
  if (body_) {
    body_->prependChain(std::move(body));
  } else {
    body_ = std::move(body);
  }
}

void HelloHandler::onEOM() noexcept {
  if (body_) {
    // Process the complete request body
    std::string bodyStr = body_->moveToFbString().toStdString();
    // Respond with the processed data
    ResponseBuilder(downstream_)
      .status(200, "OK")
      .body("Received: " + bodyStr)
      .sendWithEOM();
  } else {
    // Handle empty body
  }
}
  1. Adding custom headers to responses:
void HelloHandler::onEOM() noexcept {
  ResponseBuilder(downstream_)
    .status(200, "OK")
    .header("X-Custom-Header", "CustomValue")
    .body("Hello with custom header!")
    .sendWithEOM();
}

Getting Started

  1. Install dependencies:

    sudo apt-get install -y g++ cmake libboost-all-dev libssl-dev libgoogle-glog-dev libgflags-dev libgtest-dev
    
  2. Clone and build Proxygen:

    git clone https://github.com/facebook/proxygen.git
    cd proxygen
    ./build.sh
    
  3. Include Proxygen in your project's CMakeLists.txt:

Competitor Comparisons

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

Pros of cpprestsdk

  • Cross-platform support (Windows, Linux, macOS, iOS, Android)
  • Extensive documentation and examples
  • Built-in support for JSON parsing and manipulation

Cons of cpprestsdk

  • Heavier dependency on Boost libraries
  • Less focus on high-performance, low-latency scenarios
  • Smaller community and fewer contributors compared to Proxygen

Code Comparison

cpprestsdk:

#include <cpprest/http_client.h>

http_client client(U("http://example.com"));
client.request(methods::GET, U("/api/data"))
    .then([](http_response response) {
        // Handle response
    });

Proxygen:

#include <proxygen/httpserver/HTTPServer.h>

HTTPServerOptions options;
options.threads = 4;
HTTPServer server(std::move(options));
server.bind({"0.0.0.0", 8080});
server.start();

Both libraries provide HTTP functionality, but cpprestsdk focuses on client-side operations with a more high-level API, while Proxygen offers lower-level server-side control with a focus on performance. cpprestsdk is better suited for cross-platform applications requiring HTTP client capabilities, while Proxygen excels in building high-performance HTTP servers and proxies.

http request/response parser for c

Pros of http-parser

  • Lightweight and focused on HTTP parsing
  • Widely used and battle-tested in Node.js ecosystem
  • Easy to integrate into C/C++ projects

Cons of http-parser

  • Limited to HTTP parsing only, not a full server framework
  • Less actively maintained compared to Proxygen
  • Fewer features for modern HTTP protocols (e.g., HTTP/2, HTTP/3)

Code Comparison

http-parser:

http_parser_settings settings;
settings.on_url = on_url_callback;
settings.on_header_field = on_header_field_callback;
http_parser_init(&parser, HTTP_REQUEST);
http_parser_execute(&parser, &settings, buffer, length);

Proxygen:

class MyHandler : public proxygen::RequestHandler {
  void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept override {
    // Handle request
  }
};

Key Differences

  • Proxygen is a full-featured HTTP server framework, while http-parser focuses solely on parsing
  • http-parser is more lightweight and easier to integrate into existing projects
  • Proxygen offers more advanced features like HTTP/2 support and asynchronous processing
  • http-parser has a simpler API, while Proxygen provides a more comprehensive set of tools

Use Cases

  • http-parser: Ideal for projects needing basic HTTP parsing functionality
  • Proxygen: Better suited for building high-performance HTTP servers with modern protocol support

A C++ header-only HTTP/HTTPS server and client library

Pros of cpp-httplib

  • Lightweight and header-only library, easy to integrate into projects
  • Simple API, making it straightforward to use for basic HTTP server/client needs
  • Cross-platform compatibility (Windows, macOS, Linux)

Cons of cpp-httplib

  • Limited performance compared to Proxygen for high-concurrency scenarios
  • Fewer advanced features and customization options
  • Less suitable for large-scale, enterprise-level applications

Code Comparison

cpp-httplib:

#include <httplib.h>

int main() {
    httplib::Server svr;
    svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("Hello, World!", "text/plain");
    });
    svr.listen("localhost", 8080);
}

Proxygen:

#include <proxygen/httpserver/HTTPServer.h>

int main() {
    proxygen::HTTPServerOptions options;
    options.threads = 0;
    options.idleTimeout = std::chrono::milliseconds(60000);
    options.shutdownOn = {SIGINT, SIGTERM};
    proxygen::HTTPServer server(std::move(options));
    server.bind({{folly::SocketAddress("localhost", 8080, true)}});
    server.start();
}

Both libraries provide HTTP server functionality, but Proxygen offers more advanced features and configuration options, while cpp-httplib focuses on simplicity and ease of use.

Simple, secure & standards compliant web server for the most demanding of applications

Pros of uWebSockets

  • Lightweight and efficient, with lower memory footprint
  • Supports WebSocket compression out of the box
  • Easier to set up and use for simple WebSocket applications

Cons of uWebSockets

  • Less feature-rich compared to Proxygen's comprehensive HTTP stack
  • Limited to WebSocket and HTTP protocols
  • Smaller community and ecosystem

Code Comparison

uWebSockets:

uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
    ws->send(message, length, opCode);
});
h.listen(3000);
h.run();

Proxygen:

class EchoHandler : public proxygen::RequestHandler {
  void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override {
    responseBody_.append(std::move(body));
  }
  void onEOM() noexcept override {
    ResponseBuilder(downstream_).body(std::move(responseBody_)).sendWithEOM();
  }
};

Summary

uWebSockets is a lightweight and efficient WebSocket library, ideal for simple WebSocket applications. It offers easy setup and built-in compression support. However, it lacks the comprehensive feature set of Proxygen, which provides a full HTTP stack and is backed by Facebook's resources. Proxygen offers more flexibility for complex HTTP-based applications but may have a steeper learning curve and higher resource usage.

A curated list of awesome C++ (or C) frameworks, libraries, resources, and shiny things. Inspired by awesome-... stuff.

Pros of awesome-cpp

  • Comprehensive resource for C++ libraries, frameworks, and tools
  • Regularly updated with community contributions
  • Covers a wide range of C++ topics and use cases

Cons of awesome-cpp

  • Not a functional codebase, primarily a curated list
  • Lacks specific implementation details or performance metrics
  • May include outdated or less maintained projects

Code comparison

While a direct code comparison isn't relevant due to the nature of these repositories, here's a brief example of how they differ:

awesome-cpp:

## Networking

* [ACE](https://www.dre.vanderbilt.edu/~schmidt/ACE.html) - An OO Network Programming Toolkit in C++.
* [Boost.Asio](https://think-async.com/Asio/) - A cross-platform C++ library for network and low-level I/O programming.

proxygen:

#include <proxygen/httpserver/HTTPServer.h>
#include <proxygen/httpserver/RequestHandlerFactory.h>

using namespace proxygen;

int main(int argc, char* argv[]) {
  HTTPServerOptions options;
  options.threads = 0;
  options.idleTimeout = std::chrono::milliseconds(60000);
  // ... (additional setup)
}

awesome-cpp serves as a directory of C++ resources, while proxygen provides a functional HTTP server implementation.

An HTML5 parsing library in pure C99

Pros of Gumbo-parser

  • Lightweight and focused on HTML5 parsing
  • Easy to integrate into existing C/C++ projects
  • Designed for high performance and low memory usage

Cons of Gumbo-parser

  • Limited scope compared to Proxygen's full HTTP stack
  • Less active development and community support
  • Lacks advanced features like HTTP/2 support

Code Comparison

Gumbo-parser (parsing HTML):

GumboOutput* output = gumbo_parse("<h1>Hello, World!</h1>");
GumboNode* root = output->root;
// Process the parsed HTML tree
gumbo_destroy_output(&kGumboDefaultOptions, output);

Proxygen (handling HTTP requests):

void MyHandler::onRequest(std::unique_ptr<HTTPMessage> headers) noexcept {
  ResponseBuilder(downstream_)
    .status(200, "OK")
    .body("Hello, World!")
    .sendWithEOM();
}

Gumbo-parser focuses on HTML parsing, while Proxygen provides a comprehensive HTTP server framework. Gumbo-parser is more suitable for projects requiring HTML processing, whereas Proxygen is better for building full-featured web servers and services.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Proxygen: Facebook's C++ HTTP Libraries

Support Ukraine Linux Build Status macOS Build Status

This project comprises the core C++ HTTP abstractions used at Facebook. Internally, it is used as the basis for building many HTTP servers, proxies, and clients. This release focuses on the common HTTP abstractions and our simple HTTPServer framework. Future releases will provide simple client APIs as well. The framework supports HTTP/1.1, SPDY/3, SPDY/3.1, HTTP/2, and HTTP/3. The goal is to provide a simple, performant, and modern C++ HTTP library.

We have a Google group for general discussions at https://groups.google.com/d/forum/facebook-proxygen.

The original blog post also has more background on the project.

Learn More in This Intro Video

Explain Like I’m 5: Proxygen

Installing

Note that currently this project has been tested on Ubuntu 18.04 and Mac OSX although it likely works on many other platforms.

You will need at least 3 GiB of memory to compile proxygen and its dependencies.

Easy Install

Just run ./build.sh from the proxygen/ directory to get and build all the dependencies and proxygen. You can run the tests manually with cd _build/ && make test. Then run ./install.sh to install it. You can remove the temporary build directory (_build) and ./build.sh && ./install.sh to rebase the dependencies, and then rebuild and reinstall proxygen.

Other Platforms

If you are running on another platform, you may need to install several packages first. Proxygen and folly are all Autotools based projects.

Introduction

Directory structure and contents:

DirectoryPurpose
proxygen/external/Contains non-installed 3rd-party code proxygen depends on.
proxygen/lib/Core networking abstractions.
proxygen/lib/http/HTTP specific code. (including HTTP/2 and HTTP/3)
proxygen/lib/services/Connection management and server code.
proxygen/lib/utils/Miscellaneous helper code.
proxygen/httpserver/Contains code wrapping proxygen/lib/ for building simple C++ http servers. We recommend building on top of these APIs.

Architecture

The central abstractions to understand in proxygen/lib are the session, codec, transaction, and handler. These are the lowest level abstractions, and we don't generally recommend building off of these directly.

When bytes are read off the wire, the HTTPCodec stored inside HTTPSession parses these into higher-level objects and associates with it a transaction identifier. The codec then calls into HTTPSession which is responsible for maintaining the mapping between transaction identifier and HTTPTransaction objects. Each HTTP request/response pair has a separate HTTPTransaction object. Finally, HTTPTransaction forwards the call to a handler object which implements HTTPTransaction:: Handler. The handler is responsible for implementing business logic for the request or response.

The handler then calls back into the transaction to generate egress (whether the egress is a request or response). The call flows from the transaction back to the session, which uses the codec to convert the higher-level semantics of the particular call into the appropriate bytes to send on the wire.

The same handler and transaction interfaces are used to both create requests and handle responses. The API is generic enough to allow both. HTTPSession is specialized slightly differently depending on whether you are using the connection to issue or respond to HTTP requests.

Core Proxygen Architecture

Moving into higher levels of abstraction, proxygen/HTTP server has a simpler set of APIs and is the recommended way to interface with proxygen when acting as a server if you don't need the full control of the lower level abstractions.

The basic components here are HTTPServer, RequestHandlerFactory, and RequestHandler. An HTTPServer takes some configuration and is given a RequestHandlerFactory. Once the server is started, the installed RequestHandlerFactory spawns a RequestHandler for each HTTP request. RequestHandler is a simple interface users of the library implement. Subclasses of RequestHandler should use the inherited protected member ResponseHandler* downstream_ to send the response.

Using it

Proxygen is a library. After installing it, you can build your C++ server. Try cd ing to the directory containing the echo server at proxygen/httpserver/samples/echo/.

After building proxygen you can start the echo server with _build/proxygen/httpserver/proxygen_echo and verify it works using curl in a different terminal:

$ curl -v http://localhost:11000/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 11000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:11000
> Accept: */*
>
< HTTP/1.1 200 OK
< Request-Number: 1
< Date: Thu, 30 Oct 2014 17:07:36 GMT
< Connection: keep-alive
< Content-Length: 0
<
* Connection #0 to host localhost left intact

You can find other samples:

  • a simple server that supports HTTP/2 server push (_build/proxygen/httpserver/proxygen_push),
  • a simple server for static files (_build/proxygen/httpserver/proxygen_static)
  • a simple fwdproxy (_build/proxygen/httpserver/proxygen_proxy)
  • a curl-like client (_build/proxygen/httpclient/samples/curl/proxygen_curl)

QUIC and HTTP/3

Proxygen supports HTTP/3!

It depends on Facebook's mvfst library for the IETF QUIC transport implementation.

This comes with a handy command-line utility that can be used as an HTTP/3 server and client.

Sample usage:

_build/proxygen/httpserver/hq --mode=server
_build/proxygen/httpserver/hq --mode=client --path=/

The utility supports the qlog logging format; just start the server with the --qlogger_path option and many knobs to tune both the quic transport and the http layer.

Documentation

We use Doxygen for Proxygen's internal documentation. You can generate a copy of these docs by running doxygen Doxyfile from the project root. You'll want to look at html/namespaceproxygen.html to start. This will also generate folly documentation.

License

See LICENSE.

Contributing

Contributions to Proxygen are more than welcome. Read the guidelines in CONTRIBUTING.md. Make sure you've signed the CLA before sending in a pull request.

Whitehat

Facebook has a bounty program for the safe disclosure of security bugs. If you find a vulnerability, please go through the process outlined on that page and do not file a public issue.