1
0
mirror of https://github.com/actix/actix-website synced 2025-02-08 22:36:07 +01:00
2022-02-26 03:56:24 +00:00

40 lines
894 B
Rust

// <responder-trait>
use actix_web::{
body::BoxBody, http::header::ContentType, HttpRequest, HttpResponse, Responder,
};
use serde::Serialize;
#[derive(Serialize)]
struct MyObj {
name: &'static str,
}
// Responder
impl Responder for MyObj {
type Body = BoxBody;
fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
let body = serde_json::to_string(&self).unwrap();
// Create response and set content type
HttpResponse::Ok()
.content_type(ContentType::json())
.body(body)
}
}
async fn index() -> impl Responder {
MyObj { name: "user" }
}
// </responder-trait>
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind(("127.0.0.1", 8080))?
.run()
.await
}