Skip to content

Commit e828b7f

Browse files
committed
Init setup
0 parents  commit e828b7f

File tree

10 files changed

+334
-0
lines changed

10 files changed

+334
-0
lines changed

.github/workflows/test.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
name: Test
2+
3+
on:
4+
push:
5+
branches: [master, develop]
6+
pull_request:
7+
branches: [master, develop]
8+
9+
jobs:
10+
build:
11+
runs-on: ubuntu-latest
12+
13+
steps:
14+
- uses: actions/checkout@v2
15+
- name: Run tests
16+
run: cargo test --verbose

.gitignore

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Created by https://www.gitignore.io/api/rust,macos
2+
# Edit at https://www.gitignore.io/?templates=rust,macos
3+
4+
### macOS ###
5+
# General
6+
.DS_Store
7+
.AppleDouble
8+
.LSOverride
9+
10+
# Icon must end with two \r
11+
Icon
12+
13+
# Thumbnails
14+
._*
15+
16+
# Files that might appear in the root of a volume
17+
.DocumentRevisions-V100
18+
.fseventsd
19+
.Spotlight-V100
20+
.TemporaryItems
21+
.Trashes
22+
.VolumeIcon.icns
23+
.com.apple.timemachine.donotpresent
24+
25+
# Directories potentially created on remote AFP share
26+
.AppleDB
27+
.AppleDesktop
28+
Network Trash Folder
29+
Temporary Items
30+
.apdisk
31+
32+
### Rust ###
33+
# Generated by Cargo
34+
# will have compiled files and executables
35+
/target/
36+
37+
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
38+
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
39+
Cargo.lock
40+
41+
# These are backup files generated by rustfmt
42+
**/*.rs.bk
43+
44+
### Others ###
45+
.halt.releez.yml
46+
/.idea
47+
json-response.iml
48+
49+
# End of https://www.gitignore.io/api/rust,macos

Cargo.toml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[package]
2+
name = "json-response"
3+
version = "1.0.0"
4+
description = "A utility library to send JSON response."
5+
homepage = "https://github.com/routerify/json-response"
6+
repository = "https://github.com/routerify/json-response"
7+
keywords = ["routerify", "hyper-rs", "json", "response"]
8+
categories = ["asynchronous", "web-programming", "web-programming::http-server"]
9+
authors = ["Rousan Ali <hello@rousan.io>"]
10+
readme = "README.md"
11+
license = "MIT"
12+
edition = "2018"
13+
14+
[dependencies]
15+
routerify = "1.0"
16+
hyper = "0.13"
17+
18+
[dev-dependencies]
19+
tokio = { version = "0.2", features = ["full"] }
20+
stream-body = "0.1"

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2020 Boilerplato
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
[![Github Actions Status](https://github.com/routerify/json-response/workflows/Test/badge.svg)](https://github.com/routerify/json-response/actions)
2+
[![crates.io](https://img.shields.io/crates/v/json-response.svg)](https://crates.io/crates/json-response)
3+
[![Documentation](https://docs.rs/json-response/badge.svg)](https://docs.rs/json-response)
4+
[![MIT](https://img.shields.io/crates/l/json-response.svg)](./LICENSE)
5+
6+
# json-response
7+
8+
A utility library to send JSON response.
9+
10+
[Docs](https://docs.rs/json-response)
11+
12+
## Usage
13+
14+
First add this to your `Cargo.toml`:
15+
16+
```toml
17+
[dependencies]
18+
json-response = "1.0"
19+
```
20+
21+
An example:
22+
```rust
23+
use json_response;
24+
25+
fn main() {
26+
println!("{}", json_response::add(2, 3));
27+
}
28+
```
29+
30+
## Contributing
31+
32+
Your PRs and suggestions are always welcome.

examples/test.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
use json_response;
2+
3+
fn main() {
4+
println!("{}", json_response::add(2, 3));
5+
}

releez.yml

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
version: 1.0.0
2+
checklist:
3+
- name: Checkout develop and sync with remote
4+
type: auto
5+
run:
6+
- git checkout develop
7+
- git push
8+
- name: Check syntax
9+
type: auto
10+
run:
11+
- cargo check --release
12+
- name: Run tests
13+
type: auto
14+
run:
15+
- cargo test --release
16+
- name: Start a new release branch
17+
type: auto
18+
run:
19+
- git flow release start "v${VERSION}"
20+
- name: Make sure code is formatted
21+
type: auto
22+
run:
23+
- cargo fmt
24+
- name: Bump version
25+
type: manual
26+
instructions:
27+
- Please update version with ${VERSION} in Cargo.toml file.
28+
- Please update version with ${VERSION} in README.md file if needed.
29+
- name: Commit changes
30+
type: auto
31+
run:
32+
- git add --all && git commit -m "Bump version"
33+
- name: Finish release branch
34+
type: auto
35+
run:
36+
- git flow release finish -s "v${VERSION}"
37+
- name: Push branches and tags to Github
38+
type: auto
39+
run:
40+
- git checkout master
41+
- git push origin master
42+
- git push origin develop
43+
- git push --tags
44+
- name: Edit tag on Github
45+
type: manual
46+
instructions:
47+
- Tag is pushed to Github(https://github.com/routerify/json-response/releases). Edit it there and make it a release.
48+
- name: Publish to crates.io
49+
type: auto
50+
confirm: Are you sure to publish it to crates.io?
51+
run:
52+
- cargo publish
53+
- git checkout develop

rustfmt.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
max_width = 120
2+
tab_spaces = 4

src/lib.rs

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
//! An utility library to send JSON response.
2+
//!
3+
//! # Examples
4+
//!
5+
//! ```
6+
//! use json_response;
7+
//!
8+
//! # fn run() {
9+
//! println!("{}", json_response::add(2, 3));
10+
//! # }
11+
//! # run();
12+
//! ```
13+
14+
use crate::prelude::*;
15+
use http::StatusCode;
16+
use hyper::{header, Body, Response};
17+
use serde::Serialize;
18+
19+
pub struct JsonResponse<T = ()>
20+
where
21+
T: Serialize,
22+
{
23+
inner: Inner<T>,
24+
}
25+
26+
enum Inner<T> {
27+
Success(SuccessData<T>),
28+
Error(ErrorData),
29+
}
30+
31+
#[derive(Serialize, Debug, Clone)]
32+
#[serde(rename_all = "camelCase")]
33+
struct SuccessData<T> {
34+
status: Status,
35+
code: u16,
36+
data: T,
37+
}
38+
39+
#[derive(Serialize, Debug, Clone)]
40+
#[serde(rename_all = "camelCase")]
41+
struct ErrorData {
42+
status: Status,
43+
code: u16,
44+
message: String,
45+
}
46+
47+
#[derive(Serialize, Debug, Clone)]
48+
enum Status {
49+
#[serde(rename = "Success")]
50+
SUCCESS,
51+
#[serde(rename = "Failed")]
52+
FAILED,
53+
}
54+
55+
impl<T: Serialize> JsonResponse<T> {
56+
pub fn with_success(code: StatusCode, data: T) -> Self {
57+
JsonResponse {
58+
inner: Inner::Success(SuccessData {
59+
status: Status::SUCCESS,
60+
code: code.as_u16(),
61+
data,
62+
}),
63+
}
64+
}
65+
}
66+
67+
impl JsonResponse<()> {
68+
pub fn with_error<M: Into<String>>(code: StatusCode, message: M) -> Self {
69+
JsonResponse {
70+
inner: Inner::Error(ErrorData {
71+
status: Status::FAILED,
72+
code: code.as_u16(),
73+
message: message.into(),
74+
}),
75+
}
76+
}
77+
78+
pub fn with_error_include_code<M: Into<String>>(code: StatusCode, message: M) -> Self {
79+
Self::with_error(
80+
code,
81+
format!("{}: {}", code.canonical_reason().unwrap(), message.into()),
82+
)
83+
}
84+
85+
pub fn with_error_code(code: StatusCode) -> Self {
86+
Self::with_error(code, code.canonical_reason().unwrap().to_owned())
87+
}
88+
}
89+
90+
impl<T: Serialize> JsonResponse<T> {
91+
pub fn into_response(self) -> crate::Result<Response<Body>> {
92+
let code;
93+
let body;
94+
95+
match self.inner {
96+
Inner::Success(success_data) => {
97+
code = success_data.code;
98+
body = Body::from(
99+
serde_json::to_vec(&success_data)
100+
.context("JsonResponse: Failed to convert success data to JSON")?,
101+
);
102+
}
103+
Inner::Error(err_data) => {
104+
code = err_data.code;
105+
body = Body::from(
106+
serde_json::to_vec(&err_data).context("JsonResponse: Failed to convert error data to JSON")?,
107+
);
108+
}
109+
}
110+
111+
Ok(Response::builder()
112+
.status(StatusCode::from_u16(code).unwrap())
113+
.header(header::CONTENT_TYPE, "application/json; charset=utf-8")
114+
.body(body)
115+
.context("JsonResponse: Failed to create a response")?)
116+
}
117+
}

tusk.yml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
options:
2+
version:
3+
usage: The next release version
4+
short: v
5+
required: true
6+
tasks:
7+
setup:
8+
run:
9+
- command: cargo install cargo-watch
10+
- command: cargo install releez
11+
dev:
12+
run:
13+
- command: cargo watch --watch ./src --watch ./examples/test.rs -x 'run --example test'
14+
doc:
15+
run:
16+
- command: cargo watch -x "doc --open"
17+
release:
18+
run:
19+
- command: releez "${version}"

0 commit comments

Comments
 (0)