Created
February 23, 2021 22:40
-
-
Save inaiat/4cba1bb171ad240611690df77829e89b to your computer and use it in GitHub Desktop.
rust actix + reqwest
This file contains hidden or 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
use actix_web::{web, App, HttpResponse, HttpServer}; | |
use reqwest::Client; | |
use serde_json::Value; | |
async fn test(data: web::Data<AppState>) -> HttpResponse { | |
let client = &data.client; | |
let result = async { | |
client | |
.get("https://httpbin.org/json") | |
.send() | |
.await? | |
.error_for_status()? | |
.json::<Value>() | |
.await | |
} | |
.await; | |
match result { | |
Ok(v) => HttpResponse::Ok().content_type("application/json").body(v), | |
Err(e) => HttpResponse::InternalServerError().body(e.to_string()), | |
} | |
} | |
struct AppState { | |
client: Client, | |
} | |
#[actix_web::main] | |
async fn main() -> std::io::Result<()> { | |
let app_state = web::Data::new(AppState { | |
client: Client::new(), | |
}); | |
HttpServer::new(move || { | |
App::new() | |
.app_data(app_state.clone()) // <- register the created data | |
.route("/", web::get().to(test)) | |
}) | |
.bind(("127.0.0.1", 8080))? | |
.run() | |
.await | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment