1 基于libhv构建http服务器,实现get请求返回图片

假设获取图片接口为:http://127.0.0.1:8080/image ,通过使用libhv构建一个http服务器,实现访问该接口获取图片。

示例代码为:

#include <iostream>
#include "opencv2/opencv.hpp"
#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("/image", [](const HttpRequestPtr& req_ptr, const HttpResponseWriterPtr& writer) {
        // 读取图片
        cv::Mat img = cv::imread("example.jpg");
        std::vector<uchar> jpg;

        // 转换成jpg图片字节流
        if (!cv::imencode(".jpg", img, jpg, { cv::IMWRITE_JPEG_QUALITY, 100 }))
        {
            return response_status(writer, HTTP_STATUS_BAD_REQUEST);
        }

        if (img.empty())
        {
            return response_status(writer, HTTP_STATUS_BAD_REQUEST);
        }

        // 写返回信息
        writer->write("HTTP/1.1 200 OK\r\n");
        writer->write("Content-Type:image/jpeg\r\n");
        writer->write(std::string("Content-Length:") + std::to_string(jpg.size()) + std::string("\r\n"));
        writer->write("\r\n");
        writer->write(jpg.data(), jpg.size());
        writer->write("\r\n");
    });

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

当通过get访问该接口时,先通过opencv读取服务器图片,然后将cv::Mat编码为jpg格式,最后通过libhv的HttpResponseWriterPtr写入返回的相关信息,其中就包括请求头、图片数据、图片长度。

我们可以打开浏览器访问:http://127.0.0.1:8080/image 看是否正确显示了图片,如果可以成功访问则说明接口功能实现没有问题。