【问题标题】:boost beast partial files server delivery提升野兽部分文件服务器交付
【发布时间】:2021-01-09 10:47:50
【问题描述】:

我想知道这段代码是否来自 https://www.boost.org/doc/libs/1_70_0/libs/beast/example/http/server/async/http_server_async.cpp

    // Attempt to open the file
    beast::error_code ec;
    http::file_body::value_type body;
    body.open(path.c_str(), beast::file_mode::scan, ec);

可以通过一些文件主体操作轻松扩展以实现 http 范围字段信息。

我想避免重新实现可用的代码,如果不需要的话有自己的(posix,...)文件处理。

非常感谢您的意见!

汤姆

【问题讨论】:

    标签: c++ boost-beast


    【解决方案1】:

    最简单的方法可能是修补 boost beast 实现(见下文)。但是请确保,在这种情况下,您对 html 知之甚少,例如

    • 使用“206 部分内容”回答 html 请求
    • 使用适当的字段(内容范围)来识别文件的一部分并相应地设置响应。

    可以在此处找到有关 html 标头的重要信息:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests

    然后 boost beast 只需要对 open() 方法进行一些小改动来传递部分文件(boost/beast/http/basic_file_body.hpp)。它是用 uint64_t 实现的,但 boost::optional<> 也可以做到这一点。

    有两个主要的事情,真的很重要:

    1. seek() 到文件起始位置和
    2. 将余数(以 file_size_ 的形式)设置为数据长度(开始和结束之间的长度部分)。

    请记住,起点和终点都包含在范围请求中。 IE。部分的长度始终为end-start+1

    但是进行此更改后,请提前阅读范围响应的整体文件大小,因为 size() 方法将返回部分大小。

    template<class File>
    void
    basic_file_body<File>::
    value_type::
    open(char const* path, file_mode mode, error_code& ec, uint64_t start, uint64_t end)
    {
        // Open the file
        file_.open(path, mode, ec);
        if(ec)
            return;
    
        // Cache the size
        file_size_ = file_.size(ec);
        if(ec)
        {
            close();
            return;
        }
    
        if (end > file_size_ || end == 0)
            end = file_size_-1;
    
        if (start <= end) {
            file_.seek(start, ec);
            if(ec)
            {
                close();
                return;
            }
            file_size_ = end - start + 1;
        }
    
    }
    

    请确保:可能还有其他方法可以进行部分读取!

    汤姆

    【讨论】:

      猜你喜欢
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2018-11-01
      • 2018-07-31
      • 2021-05-11
      • 2014-08-25
      相关资源
      最近更新 更多