A Routerify
utility library to generate JSON response.
In Success
case, It generates JSON response in the following format:
json
{
"status": "success",
"code": "<status_code>",
"data": "<data>"
}
In Failed
case, It generates JSON response in the following format:
json
{
"status": "failed",
"code": "<status_code>",
"message": "<error_message>"
}
Add this to your Cargo.toml
:
toml
[dependencies]
routerify = "3"
routerify-json-response = "3"
```rust use hyper::{Body, Request, Response, Server, StatusCode}; // Import required routerifyjsonresponse methods. use routerifyjsonresponse::{jsonfailedrespwithmessage, jsonsuccessresp}; use routerify::{Router, RouterService}; use std::net::SocketAddr;
async fn listusershandler(: Request) -> Result
// Generate a success JSON response with the data in the following format:
// { "status": "success", code: 200, data: ["Alice", "John"] }
json_success_resp(&users)
}
async fn listbookshandler(: Request) -> Result
// Create a router. fn router() -> Router
{ Router::builder() // Attach the handlers. .get("/users", listusershandler) .get("/books", listbookshandler) .build() .unwrap() }async fn main() { let router = router();
// Create a Service from the router above to handle incoming requests.
let service = RouterService::new(router).unwrap();
// The address on which the server will be listening.
let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
// Create a server by passing the created service to `.serve` method.
let server = Server::bind(&addr).serve(service);
println!("App is running on: {}", addr);
if let Err(err) = server.await {
eprintln!("Server error: {}", err);
}
} ```
Your PRs and suggestions are always welcome.