Skip to content

Instantly share code, notes, and snippets.

@jbr
Created April 24, 2020 05:10
Show Gist options
  • Save jbr/d5c4fec7368eae5a372b6ae403b9c67f to your computer and use it in GitHub Desktop.
Save jbr/d5c4fec7368eae5a372b6ae403b9c67f to your computer and use it in GitHub Desktop.
surf-tide-proxy-example
[package]
name = "surf-tide-proxy-example"
version = "0.1.0"
authors = ["Jacob Rothstein <hi@jbr.me>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
surf = { git = "https://github.com/http-rs/surf", branch = "master" }
tide = { git = "https://github.com/http-rs/tide", branch = "master" }
async-std = { version = "1.5.0", features = ["attributes"]}
use tide::{Response, StatusCode};
use async_std::{fs::File, io::BufReader};
#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut app = tide::new();
app.at("proxied").get(|_| async {
let file = File::open("./Cargo.toml").await?; //just serving a random file
let reader = BufReader::new(file);
Ok(Response::new(StatusCode::Ok).body(reader))
});
app.at("proxy").get(|_| async {
let surf_response = surf::get("http://localhost:8300/proxied").await?;
let mime = surf_response.mime();
//uses the surf response as an async bufread, which should stream the response body
let mut tide_response = Response::new(surf_response.status()).body(surf_response);
if let Some(mime) = mime {
// there's currently no way to iterate over all surf headers afaik
tide_response = tide_response.set_mime(mime);
}
Ok(tide_response)
});
app.listen("localhost:8300").await?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment