#codec #http #http-request #http-response #http-1 #encoder #decoder

httpcodec

基于bytecodec crate的HTTP/1.x消息编解码器

15个版本

使用旧的Rust 2015

0.2.3 2019年8月18日
0.2.2 2018年5月19日
0.1.10 2018年5月2日
0.1.6 2018年4月30日

#969编码

Download history 866/week @ 2024-03-17 774/week @ 2024-03-24 829/week @ 2024-03-31 824/week @ 2024-04-07 965/week @ 2024-04-14 1100/week @ 2024-04-21 978/week @ 2024-04-28 901/week @ 2024-05-05 920/week @ 2024-05-12 1115/week @ 2024-05-19 580/week @ 2024-05-26 682/week @ 2024-06-02 735/week @ 2024-06-09 782/week @ 2024-06-16 940/week @ 2024-06-23 374/week @ 2024-06-30

2,879 每月下载量
13 crates中使用

MIT 许可证

85KB
2K SLoC

httpcodec

Documentation Build Status Code Coverage License: MIT

基于bytecodec crate的HTTP/1.x消息编解码器。

文档

示例

编码HTTP请求消息

use bytecodec::Encode;
use bytecodec::bytes::BytesEncoder;
use bytecodec::io::IoEncodeExt;
use httpcodec::{BodyEncoder, HttpVersion, Method, Request, RequestEncoder, RequestTarget};

let request = Request::new(
    Method::new("GET").unwrap(),
    RequestTarget::new("/foo").unwrap(),
    HttpVersion::V1_1,
    b"barbaz",
);

let mut encoder = RequestEncoder::new(BodyEncoder::new(BytesEncoder::new()));
encoder.start_encoding(request).unwrap();

let mut buf = Vec::new();
encoder.encode_all(&mut buf).unwrap();
assert_eq!(buf, "GET /foo HTTP/1.1\r\nContent-Length: 6\r\n\r\nbarbaz".as_bytes());

解码HTTP响应消息

use bytecodec::bytes::RemainingBytesDecoder;
use bytecodec::io::IoDecodeExt;
use httpcodec::{BodyDecoder, HttpVersion, ResponseDecoder};

let mut decoder =
    ResponseDecoder::<BodyDecoder<RemainingBytesDecoder>>::default();

let input = b"HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nbarbaz";
let response = decoder.decode_exact(input.as_ref()).unwrap();

assert_eq!(response.http_version(), HttpVersion::V1_0);
assert_eq!(response.status_code().as_u16(), 200);
assert_eq!(response.reason_phrase().as_str(), "OK");
assert_eq!(
    response.header()
        .fields()
        .map(|f| (f.name().to_owned(), f.value().to_owned()))
        .collect::<Vec<_>>(),
    vec![("Content-Length".to_owned(), "6".to_owned())]
);
assert_eq!(response.body(), b"barbaz");

参考

  • RFC 7230 超文本传输协议 (HTTP/1.1): 消息语法和路由

依赖项

~2MB
~42K SLoC