pistacheio / pistache

A high-performance REST toolkit written in C++
https://pistacheio.github.io/pistache/
Apache License 2.0
3.21k stars 701 forks source link

how to get the http header info in server by pistache function or class? #818

Open daxue2017 opened 4 years ago

daxue2017 commented 4 years ago

how to get the http header info in server by pistache function or class? for example:

General

Request URL: Request Method: Status Code Remote Address

### Response Headers Access-Control-Allow-Credentials Access-Control-Allow-Origin Content-Length Date

Request Headers

Accept Accept-Encoding: Accept-Language Connetion: Host: Origin Referer User-Agent

ljluestc commented 1 week ago

#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <iostream>

using namespace Pistache;

class HttpHandler : public Http::Handler {
public:
    HTTP_PROTOTYPE(HttpHandler)

    void onRequest(const Http::Request& request, Http::ResponseWriter response) override {
        // Extract general request information
        std::cout << "Request URL: " << request.resource() << std::endl;
        std::cout << "Request Method: " << request.method() << std::endl;
        std::cout << "Remote Address: " << request.remoteAddress().host() << std::endl;

        // Print request headers
        std::cout << "Request Headers:" << std::endl;
        for (const auto& header : request.headers()) {
            std::cout << header.first << ": " << header.second << std::endl;
        }

        // Create a response
        response.headers().add<Http::Header::ContentType>(MIME(Text, Plain));
        response.send(Http::Code::Ok, "Hello, World!");

        // Optionally add response headers
        response.headers().add<Http::Header::AccessControlAllowOrigin>("*");
        response.headers().add<Http::Header::AccessControlAllowCredentials>("true");
        response.headers().add<Http::Header::ContentLength>(std::to_string(13)); // "Hello, World!" length
        response.headers().add<Http::Header::Date>(Http::Header::Date::formatNow());
    }
};

int main() {
    // Create an HTTP server
    Port port(9080);
    int threads = 2;

    auto opts = Http::Endpoint::options()
                    .threads(threads);

    Http::Endpoint server(Address(Ipv4::any(), port));
    server.init(opts);

    // Set up the router
    Rest::Router router;
    Rest::Routes::Get(router, "/hello", Rest::Routes::bind(&HttpHandler::onRequest));

    server.setHandler(router.handler());

    // Start the server
    server.serve();
    return 0;
}
kiplingw commented 1 week ago

@ljluestc, I think he's asking about server side and not client side.