graphul 1.0.0

Optimize, speed, scale your microservices and save money 💵
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
<p align="center">
  <a href="https://github.com/rustful-rs/rustful">
    <img alt="Graphul" height="200" src="./img/logo.png">
  </a>
  <br>
</p>

<p>
<b>Graphul</b> is an <a href="https://github.com/expressjs/express">Express</a> inspired <b>web framework</b> using a powerful extractor system. Designed to improve, speed, and scale your microservices with a friendly syntax, Graphul is built with <a href="https://www.rust-lang.org/">Rust</a>. that means Graphul gets memory safety, reliability, concurrency, and performance for free. helping to save money on infrastructure.
</p>


## [Buy a Coffee with Bitcoin ☕️]https://github.com/graphul-rs/graphul/blob/main/BUY-A-COFFEE.md

[![Discord](https://img.shields.io/discord/1096163462767444130?label=Discord)](https://discord.gg/3WCMgT3KCS)
Join our Discord server to chat with others in the Graphul community!

## ⚡️ Quickstart

```rust
use graphul::{Graphul, http::Methods};


#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.get("/", || async {
        "Hello, World 👋!"
    });

    app.run("127.0.0.1:8000").await;
}
```

## 👀 Examples

Listed below are some of the common examples. If you want to see more code examples , please visit our [Examples Folder](https://github.com/graphul-rs/graphul/tree/main/examples)

## common examples

- [Context]#-context
- [JSON]#-json
- [Resource]#-resource
- [Static files]#-static-files
- [Groups]#-groups
- [Share state]#-share-state
- [Share state with Resource]#-share-state-with-resource
- [Middleware]#-middleware
- [Routers]#-routers
- [Templates]#-templates
- [Swagger - OpenAPI]https://github.com/graphul-rs/graphul/tree/main/examples/utoipa-swagger-ui
- ⭐️ help us by adding a star on [GitHub Star]https://github.com/graphul-rs/graphul/stargazers to the project

## 🛫 Graphul vs most famous frameworks out there

<img alt="Graphul" width="700" src="./img/compare.png">

## 📖 Context

```rust
use graphul::{http::Methods, Context, Graphul};

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    // /samuel?country=Colombia
    app.get("/:name", |c: Context| async move {
        /*
           statically typed query param extraction
           let value: Json<MyType> = match c.parse_params().await
           let value: Json<MyType> = match c.parse_query().await
        */

        let name = c.params("name");
        let country = c.query("country");
        let ip = c.ip();

        format!("My name is {name}, I'm from {country}, my IP is {ip}",)
    });

    app.run("127.0.0.1:8000").await;
}
```

## 📖 JSON

```rust
use graphul::{Graphul, http::Methods, extract::Json};
use serde_json::json;

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.get("/", || async {
        Json(json!({
            "name": "full_name",
            "age": 98,
            "phones": [
                format!("+44 {}", 8)
            ]
        }))
    });

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Resource

```rust
use std::collections::HashMap;

use graphul::{
    async_trait,
    extract::Json,
    http::{resource::Resource, response::Response, StatusCode},
    Context, Graphul, IntoResponse,
};
use serde_json::json;

type ResValue = HashMap<String, String>;

struct Article;

#[async_trait]
impl Resource for Article {
    async fn get(c: Context) -> Response {
        let posts = json!({
            "posts": ["Article 1", "Article 2", "Article ..."]
        });
        (StatusCode::OK, c.json(posts)).into_response()
    }

    async fn post(c: Context) -> Response {
        // you can use ctx.parse_params() or ctx.parse_query()
        let value: Json<ResValue> = match c.payload().await {
            Ok(data) => data,
            Err(err) => return err.into_response(),
        };

        (StatusCode::CREATED, value).into_response()
    }

    // you can use put, delete, head, patch and trace
}

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.resource("/article", Article);

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Static files

```rust
use graphul::{Graphul, FolderConfig, FileConfig};

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    // path = "/static", dir = public
    app.static_files("/static", "public", FolderConfig::default());

    // single page application
    app.static_files("/", "app/build", FolderConfig::spa());

    app.static_file("/about", "templates/about.html", FileConfig::default());

    app.run("127.0.0.1:8000").await;
}
```

### 🌟 static files with custom config

```rust
use graphul::{Graphul, FolderConfig, FileConfig};

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.static_files("/", "templates", FolderConfig {
        // single page application
        spa: false,
        // it support gzip, brotli and deflate
        compress: true,
        // Set a specific read buffer chunk size.
        // The default capacity is 64kb.
        chunk_size: None,
        // If the requested path is a directory append `index.html`.
        // This is useful for static sites.
        index: true,
        // fallback - This file will be called if there is no file at the path of the request.
        not_found: Some("templates/404.html"), // or None
    });

    app.static_file("/path", "templates/about.html", FileConfig {
        // it support gzip, brotli and deflate
        compress: true,
        chunk_size: Some(65536) // buffer capacity 64KiB
    });

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Groups


```rust
use graphul::{
    extract::{Path, Json},
    Graphul,
    http::{ Methods, StatusCode }, IntoResponse
};

use serde_json::json;

async fn index() -> &'static str {
    "index handler"
}

async fn name(Path(name): Path<String>) -> impl IntoResponse {
    let user = json!({
        "response": format!("my name is {}", name)
    });
    (StatusCode::CREATED, Json(user)).into_response()
}

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    // GROUP /api
    let mut api = app.group("api");

    // GROUP /api/user
    let mut user = api.group("user");

    // GET POST PUT DELETE ... /api/user
    user.resource("/", Article);

    // GET /api/user/samuel
    user.get("/:name", name);

    // GROUP /api/post
    let mut post = api.group("post");

    // GET /api/post
    post.get("/", index);

    // GET /api/post/all
    post.get("/all", || async move {
        Json(json!({"message": "hello world!"}))
    });

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Share state

```rust
use graphul::{http::Methods, extract::State, Graphul};

#[derive(Clone)]
struct AppState {
    data: String
}

#[tokio::main]
async fn main() {
    let state = AppState { data: "Hello, World 👋!".to_string() };
    let mut app = Graphul::share_state(state);

    app.get("/", |State(state): State<AppState>| async {
        state.data
    });

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Share state with Resource

```rust
use graphul::{
    async_trait,
    http::{resource::Resource, response::Response, StatusCode},
    Context, Graphul, IntoResponse,
};
use serde_json::json;

struct Article;

#[derive(Clone)]
struct AppState {
    data: Vec<&'static str>,
}

#[async_trait]
impl Resource<AppState> for Article {

    async fn get(ctx: Context<AppState>) -> Response {
        let article = ctx.state();

        let posts = json!({
            "posts": article.data,
        });
        (StatusCode::OK, ctx.json(posts)).into_response()
    }

    // you can use post, put, delete, head, patch and trace

}

#[tokio::main]
async fn main() {
    let state = AppState {
        data: vec!["Article 1", "Article 2", "Article 3"],
    };
    let mut app = Graphul::share_state(state);

    app.resource("/article", Article);

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Middleware

- [Example using tracing]https://github.com/graphul-rs/graphul/tree/main/examples/tracing-middleware

```rust
use graphul::{
    Req,
    middleware::{self, Next},
    http::{response::Response,Methods},
    Graphul
};

async fn my_middleware( request: Req, next: Next ) -> Response {

    // your logic

    next.run(request).await
}

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.get("/", || async {
        "hello world!"
    });
    app.middleware(middleware::from_fn(my_middleware));

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Routers

- [Example Multiple Routers]https://github.com/graphul-rs/graphul/tree/main/examples/multiple-routers

```rust
use graphul::{
    Req,
    middleware::{self, Next},
    http::{response::Response,Methods},
    Graphul
};

async fn my_router() -> Graphul {
    let mut router = Graphul::router();

    router.get("/hi", || async {
        "Hey! :)"
    });
    // this middleware will be available only on this router
    router.middleware(middleware::from_fn(my_middleware));

    router
}

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.get("/", || async {
        "hello world!"
    });

    app.add_router(my_router().await);

    app.run("127.0.0.1:8000").await;
}
```

## 📖 Templates

```rust
use graphul::{
    http::Methods,
    Context, Graphul, template::HtmlTemplate,
};
use askama::Template;

#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate {
    name: String,
}

#[tokio::main]
async fn main() {
    let mut app = Graphul::new();

    app.get("/:name", |c: Context| async  move {
        let template = HelloTemplate { name: c.params("name") };
        HtmlTemplate(template)
    });

    app.run("127.0.0.1:8000").await;
}
```

## License

This project is licensed under the [MIT license](https://github.com/graphul-rs/graphul/blob/main/LICENSE).

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in `Graphul` by you, shall be licensed as MIT, without any
additional terms or conditions.