1
0
mirror of https://github.com/actix/actix-website synced 2025-02-02 12:19:04 +01:00

Update responder-trait

This commit is contained in:
Yuki Okushi 2019-12-29 02:47:27 +09:00
parent 4f2f930349
commit 2cd3428c8e
2 changed files with 13 additions and 10 deletions

View File

@ -4,6 +4,8 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
futures = "0.3.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"

View File

@ -1,6 +1,7 @@
// <responder-trait> // <responder-trait>
use actix_web::{Error, HttpRequest, HttpResponse, Responder}; use actix_web::{Error, HttpRequest, HttpResponse, Responder};
use serde::Serialize; use serde::Serialize;
use futures::future::{ready, Ready};
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {
@ -10,29 +11,29 @@ struct MyObj {
// Responder // Responder
impl Responder for MyObj { impl Responder for MyObj {
type Error = Error; type Error = Error;
type Future = Result<HttpResponse, Error>; type Future = Ready<Result<HttpResponse, Error>>;
fn respond_to(self, _req: &HttpRequest) -> Self::Future { fn respond_to(self, _req: &HttpRequest) -> Self::Future {
let body = serde_json::to_string(&self)?; let body = serde_json::to_string(&self).unwrap();
// Create response and set content type // Create response and set content type
Ok(HttpResponse::Ok() ready(Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
.body(body)) .body(body)))
} }
} }
fn index() -> impl Responder { async fn index() -> impl Responder {
MyObj { name: "user" } MyObj { name: "user" }
} }
// </responder-trait> // </responder-trait>
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route("/", web::get().to(index))) HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }