1
0
mirror of https://github.com/actix/actix-website synced 2025-02-09 23:05:37 +01:00

40 lines
894 B
Rust
Raw Normal View History

2019-06-20 02:04:22 -04:00
// <responder-trait>
2022-02-26 03:56:24 +00:00
use actix_web::{
body::BoxBody, http::header::ContentType, HttpRequest, HttpResponse, Responder,
};
2020-11-27 01:10:05 +00:00
use serde::Serialize;
2019-06-15 16:37:08 -04:00
#[derive(Serialize)]
struct MyObj {
name: &'static str,
}
// Responder
impl Responder for MyObj {
2022-02-26 03:56:24 +00:00
type Body = BoxBody;
2019-06-15 16:37:08 -04:00
2022-02-26 03:56:24 +00:00
fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
2019-12-29 02:47:27 +09:00
let body = serde_json::to_string(&self).unwrap();
2019-06-15 16:37:08 -04:00
// Create response and set content type
2022-02-26 03:56:24 +00:00
HttpResponse::Ok()
.content_type(ContentType::json())
.body(body)
2019-06-15 16:37:08 -04:00
}
}
2019-12-29 02:47:27 +09:00
async fn index() -> impl Responder {
2019-06-15 16:37:08 -04:00
MyObj { name: "user" }
}
2019-06-20 02:04:22 -04:00
// </responder-trait>
2019-06-15 16:37:08 -04:00
2020-09-12 16:21:54 +01:00
#[actix_web::main]
2019-12-29 02:47:27 +09:00
async fn main() -> std::io::Result<()> {
2019-06-28 13:31:30 -04:00
use actix_web::{web, App, HttpServer};
2019-06-15 16:37:08 -04:00
HttpServer::new(|| App::new().route("/", web::get().to(index)))
2022-02-26 03:56:24 +00:00
.bind(("127.0.0.1", 8080))?
2019-06-15 16:37:08 -04:00
.run()
2019-12-29 02:47:27 +09:00
.await
2019-06-15 16:37:08 -04:00
}