json_response/lib.rs
1//! A utility library to send JSON response for [`Routerify`](https://github.com/routerify/routerify) and the Rust HTTP library [`hyper.rs`](https://hyper.rs/) apps.
2//!
3//! In `Success` case, It generates JSON response in the following format:
4//!
5//! ```json
6//! {
7//! "status": "success",
8//! "code": "<status_code>",
9//! "data": "<data>"
10//! }
11//! ```
12//!
13//! In `Failed` case, It generates JSON response in the following format:
14//!
15//! ```json
16//! {
17//! "status": "failed",
18//! "code": "<status_code>",
19//! "message": "<error_message>"
20//! }
21//! ```
22//!
23//! # Examples
24//!
25//! ```no_run
26//! use hyper::{Body, Request, Response, Server, StatusCode};
27//! // Import required json_response methods.
28//! use json_response::{json_failed_resp_with_message, json_success_resp};
29//! use routerify::{Router, RouterService};
30//! use std::net::SocketAddr;
31//!
32//! async fn list_users_handler(_: Request<Body>) -> Result<Response<Body>, routerify::Error> {
33//! // Fetch response data from somewhere.
34//! let users = ["Alice", "John"];
35//!
36//! // Generate a success JSON response with the data in the following format:
37//! // { "status": "success", code: 200, data: ["Alice", "John"] }
38//! json_success_resp(&users)
39//! }
40//!
41//! async fn list_books_handler(_: Request<Body>) -> Result<Response<Body>, routerify::Error> {
42//! // Generate a failed JSON response in the following format:
43//! // { "status": "failed", code: 500, data: "Internal Server Error: Couldn't fetch book list from database" }
44//! json_failed_resp_with_message(
45//! StatusCode::INTERNAL_SERVER_ERROR,
46//! "Couldn't fetch book list from database",
47//! )
48//! }
49//!
50//! // Create a router.
51//! fn router() -> Router<Body, routerify::Error> {
52//! Router::builder()
53//! // Attach the handlers.
54//! .get("/users", list_users_handler)
55//! .get("/books", list_books_handler)
56//! .build()
57//! .unwrap()
58//! }
59//!
60//! #[tokio::main]
61//! async fn main() {
62//! let router = router();
63//!
64//! // Create a Service from the router above to handle incoming requests.
65//! let service = RouterService::new(router);
66//!
67//! // The address on which the server will be listening.
68//! let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
69//!
70//! // Create a server by passing the created service to `.serve` method.
71//! let server = Server::bind(&addr).serve(service);
72//!
73//! println!("App is running on: {}", addr);
74//! if let Err(err) = server.await {
75//! eprintln!("Server error: {}", err);
76//! }
77//! }
78//! ```
79
80pub use failed_resp::{json_failed_resp, json_failed_resp_with_message};
81pub use success_resp::{json_success_resp, json_success_resp_with_code};
82
83mod failed_resp;
84mod gen_resp;
85mod success_resp;