wasmesh_proto/
http_method.rs1use std::ops::Deref;
2
3use bytes::Bytes;
4use protobuf::ProtobufEnum;
5
6use crate::proto::{HttpMethod, HttpRequest, HttpResponse};
7
8impl HttpMethod {
9 pub fn as_str(&self) -> &'static str {
10 ProtobufEnum::descriptor(self).name()
11 }
12}
13
14impl Deref for HttpMethod {
15 type Target = hyper::Method;
16
17 fn deref(&self) -> &Self::Target {
18 match self {
19 HttpMethod::GET => { &hyper::Method::GET }
20 HttpMethod::HEAD => { &hyper::Method::HEAD }
21 HttpMethod::POST => { &hyper::Method::POST }
22 HttpMethod::PUT => { &hyper::Method::PUT }
23 HttpMethod::DELETE => { &hyper::Method::DELETE }
24 HttpMethod::CONNECT => { &hyper::Method::CONNECT }
25 HttpMethod::OPTIONS => { &hyper::Method::OPTIONS }
26 HttpMethod::TRACE => { &hyper::Method::TRACE }
27 HttpMethod::PATCH => { &hyper::Method::PATCH }
28 }
29 }
30}
31
32impl From<hyper::Method> for HttpMethod {
33 fn from(method: hyper::Method) -> Self {
34 match method {
35 hyper::Method::GET => { HttpMethod::GET }
36 hyper::Method::HEAD => { HttpMethod::HEAD }
37 hyper::Method::POST => { HttpMethod::POST }
38 hyper::Method::PUT => { HttpMethod::PUT }
39 hyper::Method::DELETE => { HttpMethod::DELETE }
40 hyper::Method::CONNECT => { HttpMethod::CONNECT }
41 hyper::Method::OPTIONS => { HttpMethod::OPTIONS }
42 hyper::Method::TRACE => { HttpMethod::TRACE }
43 hyper::Method::PATCH => { HttpMethod::PATCH }
44 _ => { HttpMethod::GET }
45 }
46 }
47}
48
49impl HttpRequest {
50 pub async fn from(req: hyper::Request<hyper::Body>) -> Self {
51 let mut msg = HttpRequest::new();
52 msg.set_url(req.uri().to_string());
53 msg.set_method(req.method().clone().into());
54 let (parts, body) = req.into_parts();
55 let body = hyper::body::to_bytes(body).await.map_or_else(|_| Bytes::new(), |v| v);
56 for x in parts.headers.iter() {
57 msg.headers.insert(
58 x.0.to_string(),
59 x.1
60 .to_str()
61 .map_or_else(|_| String::new(), |s| s.to_string()),
62 );
63 }
64 msg.set_body(body);
65 msg
66 }
67}
68
69impl From<HttpResponse> for hyper::Response<hyper::Body> {
70 fn from(mut msg: HttpResponse) -> Self {
71 let mut resp = hyper::Response::builder();
72 for x in msg.headers.iter() {
73 resp = resp.header(x.0, x.1);
74 }
75 if msg.status <= 0 {
76 msg.set_status(200)
77 }
78 resp = resp.status(msg.status as u16);
79 resp.body(hyper::Body::from(msg.body)).unwrap()
80 }
81}