Created
September 12, 2020 02:04
-
-
Save BillBarnhill/d492c1f4eb59c7b403f97c114a6d68a4 to your computer and use it in GitHub Desktop.
Rust snippet showing how to use state with Tide
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Clone)] | |
pub struct AppState { | |
name : String | |
} | |
pub struct App { | |
server : tide::Server<AppState> | |
} | |
impl App { | |
pub async fn get_body(_req: tide::Request<AppState>) -> tide::Result<tide::Response<>> { | |
Ok(tide::Response::builder(203) | |
.body("body") | |
.content_type(tide::http::mime::HTML) | |
.header("custom-header", "value") | |
.build() ) | |
} | |
pub async fn get_hello(req: tide::Request<AppState>) -> tide::Result<tide::Response<>> { | |
Ok(tide::Response::builder(203) | |
.body(format!("Hello, {}",req.state().name)) | |
.content_type(tide::http::mime::HTML) | |
.header("custom-header", "value") | |
.build() ) | |
} | |
pub fn new(state: AppState) -> Self { | |
let mut result = Self { | |
server : tide::with_state(state) | |
}; | |
result.server.at("/hello").get(App::get_hello); | |
result.server.at("/").get(App::get_body); | |
result | |
} | |
pub async fn run(self) -> tide::Result<()> { | |
tide::log::start(); | |
self.server.listen("127.0.0.1:8000").await?; | |
Ok(()) | |
} | |
} | |
#[async_std::main] | |
async fn main() -> tide::Result<()> { | |
println!("Starting..."); | |
let state = AppState { | |
name: "Todd".to_string() | |
}; | |
let app = App::new(state); | |
app.run().await?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment