1 基于libhv构建http服务器

1.1 libhv官方提供的简单示例

libhv提供了简单的构建http服务器的代码示例

#include "hv/HttpServer.h"

int main() {
    HttpService router;
    router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) {
        return resp->String("pong");
    });

    router.GET("/data", [](HttpRequest* req, HttpResponse* resp) {
        static char data[] = "0123456789";
        return resp->Data(data, 10);
    });

    router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) {
        return resp->Json(router.Paths());
    });

    router.POST("/echo", [](const HttpContextPtr& ctx) {
        return ctx->send(ctx->body(), ctx->type());
    });

    http_server_t server;
    server.port = 8080;
    server.service = &router;
    http_server_run(&server);
    return 0;
}

示例代码文件为:http_server_test.cpp,另外http服务器还可参考这个示例httpd

不过上述代码中get和post接口请求的都是传入HttpRequest* req, HttpResponse* resp这种参数,本文将使用HttpContext*作为参数传递实现接口功能。

1.2 实现get接口返回json数据

以下是我基于libhv实现get接口返回json数据的代码示例

#include <iostream>
#include "hv/HttpServer.h"

static int response_status(HttpResponse* resp, int code = 200, const char* message = NULL) {
    if (message == NULL) message = http_status_str((enum http_status)code);
    resp->Set("code", code);
    resp->Set("message", message);
    return code;
}
static int response_status(const HttpResponseWriterPtr& writer, int code = 200, const char* message = NULL) {
    response_status(writer->response.get(), code, message);
    writer->End();
    return code;
}
static int response_status(const HttpContextPtr& ctx, int code = 200, const char* message = NULL) {
    response_status(ctx->response.get(), code, message);
    ctx->send();
    return code;
}

int main() {
    hv::HttpService router;
    router.GET("/message", [](const HttpContextPtr& ctx) {
        std::string text = ctx->param("text");

        if (text.empty())
        {
            return response_status(ctx, HTTP_STATUS_BAD_REQUEST);
        }

        hv::Json result_json;
        result_json["text"] = text;
        result_json["message"] = "request success";

        std::string result_json_str = result_json.dump();

        return ctx->send(result_json_str, APPLICATION_JSON);
    });

    hv::HttpServer http_server;
    http_server.setPort(8080);
    http_server.registerHttpService(&router);
    std::cout << "run success" << std::endl;
    http_server.run();
    return 0;
}

1.3 实现post接口返回json数据

以下是我基于libhv实现post接口返回json数据的代码示例,在请求时需将Content-Type设置为application/json,body中传入json数据

{
    "text":"hello world"
}

http服务器代码为

#include <iostream>
#include "hv/HttpServer.h"

static int response_status(HttpResponse* resp, int code = 200, const char* message = NULL) {
    if (message == NULL) message = http_status_str((enum http_status)code);
    resp->Set("code", code);
    resp->Set("message", message);
    return code;
}
static int response_status(const HttpResponseWriterPtr& writer, int code = 200, const char* message = NULL) {
    response_status(writer->response.get(), code, message);
    writer->End();
    return code;
}
static int response_status(const HttpContextPtr& ctx, int code = 200, const char* message = NULL) {
    response_status(ctx->response.get(), code, message);
    ctx->send();
    return code;
}

int main() {
    hv::HttpService router;
    router.POST("/message", [](const HttpContextPtr& ctx) {
        if (!ctx->is(APPLICATION_JSON))
        {
            return response_status(ctx, HTTP_STATUS_BAD_REQUEST);
        }

        auto req_json = ctx->json();
        std::string text = req_json["text"].get<std::string>();

        if (text.empty())
        {
            return response_status(ctx, HTTP_STATUS_BAD_REQUEST);
        }

        hv::Json result_json;
        result_json["text"] = text;
        result_json["message"] = "request success";

        std::string result_json_str = result_json.dump();

        return ctx->send(result_json_str, APPLICATION_JSON);
        });

    hv::HttpServer http_server;
    http_server.setPort(8080);
    http_server.registerHttpService(&router);
    std::cout << "run success" << std::endl;
    http_server.run();
    return 0;
}

参考