Setup a basic API route

This commit is contained in:
Valentin Tolmer
2021-05-09 11:52:53 +02:00
parent 4091d21277
commit 4ae94839f2
5 changed files with 42 additions and 8 deletions

View File

@@ -4,7 +4,7 @@ use actix_files::{Files, NamedFile};
use actix_http::HttpServiceBuilder;
use actix_server::ServerBuilder;
use actix_service::map_config;
use actix_web::{dev::AppConfig, web, App, HttpRequest};
use actix_web::{dev::AppConfig, web, App, HttpRequest, HttpResponse};
use anyhow::{Context, Result};
use std::path::PathBuf;
@@ -16,6 +16,34 @@ async fn index(req: HttpRequest) -> actix_web::Result<NamedFile> {
Ok(NamedFile::open(path)?)
}
type ApiResult<M> = actix_web::Either<web::Json<M>, HttpResponse>;
async fn user_list_handler(_info: web::Json<ListUsersRequest>) -> ApiResult<Vec<User>> {
if true {
ApiResult::Right(HttpResponse::Conflict().finish())
} else {
ApiResult::Left(web::Json(Vec::<User>::new()))
}
}
fn api_config(cfg: &mut web::ServiceConfig) {
let json_config = web::JsonConfig::default()
.limit(4096)
.error_handler(|err, _req| {
// create custom error response
actix_web::error::InternalError::from_response(
err,
HttpResponse::Conflict().finish().into(),
)
.into()
});
cfg.service(
web::resource("/users")
.app_data(json_config)
.route(web::post().to(user_list_handler)),
);
}
pub fn build_tcp_server<Backend>(
config: &Configuration,
_backend_handler: Backend,
@@ -34,6 +62,8 @@ where
"/{filename:(index\\.html|main\\.js)?}",
web::get().to(index),
)
// API endpoint.
.service(web::scope("/api").configure(api_config))
// Serve the /pkg path with the compiled WASM app.
.service(Files::new("/pkg", "./app/pkg")),
|_| AppConfig::default(),