snapview / tokio-tungstenite

Future-based Tungstenite for Tokio. Lightweight stream-based WebSocket implementation
MIT License
1.88k stars 236 forks source link

Allow passing cookies to async_connect() #255

Closed hmeine closed 1 year ago

hmeine commented 1 year ago

I want to connect to a WS endpoint that requires a login cookie. Looking at the code, I think I have to copy impl IntoClientRequest for Uri in order to add my headers, right? I would have liked to be able to reuse that code. Or should I use the high-level reqwest library (which has https://docs.rs/reqwest/0.11.4/reqwest/cookie/struct.Jar.html#method.add_cookie_str) to open my connection and then pass it into tokio-tungstenite? (Caveat: I do not have a lot of practical experience with async rust, tokio or even networking yet, but I do have solid background knowledge.)

(Since I have also implemented the axum-based server side, an alternative could also be to get rid of the cookie mechanism for this endpoint and to use a custom message. I would not like that a lot, since I have lots of other endpoints that all follow the same pattern with the login cookie.)

daniel-abramov commented 1 year ago

You can use our IntoClientRequest trait that we provide for a string to generate a ready-to-go request and then just modify the parts by e.g. adding or modifying headers that you need.

            let mut request = your_url.into_client_request().unwrap();
            request.headers_mut().insert("User-Agent", "Some-custom/UserAgent".parse().unwrap()); // Or other modifications
hmeine commented 1 year ago

Oh, that makes perfect sense, thank you – I am not familiar with the Request API and thought that it was too late after the builder was done.