1
0
mirror of https://github.com/actix/actix-website synced 2025-06-27 15:39:02 +02:00

First pass at Handlers chapter.

This commit is contained in:
Cameron Dershem
2019-06-15 16:37:08 -04:00
parent ebc6a44650
commit f7b22dfdc0
13 changed files with 238 additions and 184 deletions

View File

@ -0,0 +1,9 @@
[package]
name = "responder-trait"
version = "0.1.0"
edition = "2018"
[dependencies]
actix-web = "1.0"
serde = "1.0"
serde_json = "1.0"

View File

@ -0,0 +1,37 @@
// <main>
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder};
use serde::Serialize;
use serde_json;
#[derive(Serialize)]
struct MyObj {
name: &'static str,
}
// Responder
impl Responder for MyObj {
type Error = Error;
type Future = Result<HttpResponse, Error>;
fn respond_to(self, _req: &HttpRequest) -> Self::Future {
let body = serde_json::to_string(&self)?;
// Create response and set content type
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(body))
}
}
fn index(_req: HttpRequest) -> impl Responder {
MyObj { name: "user" }
}
fn main() {
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}
// </main>