Could you provide an example on how to use it?
This is what I've got so far:
use actix_web::{web, App, HttpResponse, HttpServer, Responder, Result};
use actix_web::http::{StatusCode};
async fn index() -> impl Responder {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body("
<h1>Home</h1>
")
}
async fn index2() -> Result<HttpResponse> {
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body("<h1>Rofl</h1>"))
}
async fn rofl() -> Result<HttpResponse> {
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body("<h1 style='color: red;'>Rofl pagina</h1>"))
}
async fn not_found() -> Result<HttpResponse> {
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body("<h1>Error 404</h1>"))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(
web::resource("/index.html").route(web::get().to(index))
)
.default_service(
web::route().to(not_found)
)
//Way to bind unfound pages to errro 404 page
})
.bind("127.0.0.1:8087")?
.run()
.await
}
How do. I make multiple routes inApp::new().service()
? Now it's only working for index.html
.
And the default_service is just returning a blank page instead of a customized Error 404-message.
Edit:
Got it working with the following code:
use actix_web::{web, App, HttpResponse, HttpServer, Responder, Result};
use actix_web::http::{StatusCode};
async fn index() -> impl Responder {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body("
<h1>Home</h1>
")
}
async fn about() -> Result<HttpResponse> {
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body("<h1>About</h1>"))
}
async fn not_found() -> Result<HttpResponse> {
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body("<h1>Error 404</h1>"))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(web::resource("/index.html").route(web::get().to(index)))
.service(web::resource("/about.html").route(web::get().to(about)))
.default_service(
web::route().to(not_found)
)
//Way to bind unfound pages to errro 404 page
})
.bind("127.0.0.1:8087")?
.run()
.await
}