Search code examples
rusthyper

Can you build a hyper::Request from a String?


I'm trying to write an intercepting proxy. I originally used hyper as a server, as that was relatively straightforward, but if a request was malformed, hyper returned a response before I could pass the request on to the upstream server. I'd like to avoid that so I'm looking to use tokio::net::TcpListener to receive requests from the browser, and then use hyper as a client to forward the request to the remote server.

As I'm using the TcpListener and subsequesnt TcpStream the request comes through as u8 which I'm then converting to a String. Is there a way to easily convert this to a hyper::Request or would I need to write the code to convert this myself?

If the latter, does anyone have any suggestions for an alternative library that would allow me to create an HTTP request from a string?


Solution

  • Update

    I found out you could have HTTP request being parsed from bytes using this crate from seanmonstar (the same author from Hyper):

    https://github.com/seanmonstar/httparse

    Perhaps using your TCP Stream and consuming the incoming bytes using this httparse crate would be enough.

    Original Answer

    If I'm not mistaken you are trying to create an instance of hyper::Request from a byte stream or a byte array (&[u8]) that you are getting from the TcpListener.

    To have a Hyper server handle requests properly and also use your already existent TCP Listener you could make use of: https://docs.rs/hyper/0.14.11/hyper/server/struct.Server.html#method.from_tcp

    And then you could use this other crate to have that request streamed to the proxied server: https://github.com/tafia/hyper-proxy