Skip to content

Commit 1f99a5e

Browse files
committed
docs: ✨ docs: ✨ added routes and controllers docs
1 parent e931e42 commit 1f99a5e

File tree

9 files changed

+261
-92
lines changed

9 files changed

+261
-92
lines changed

docs/.vitepress/config.mts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,16 @@ export default defineConfig({
5555
},
5656
{
5757
text: "Controllers and Routes",
58-
link: "/en/key-concepts/controllers-routes",
58+
items: [
59+
{
60+
text: "Defining Controllers",
61+
link: "/en/key-concepts/controllers/definition",
62+
},
63+
{
64+
text: "Defining Routes",
65+
link: "/en/key-concepts/controllers/routes",
66+
},
67+
],
5968
},
6069
{
6170
text: "Context and Request Handling",
@@ -168,8 +177,17 @@ export default defineConfig({
168177
],
169178
},
170179
{
171-
text: "Controladores y Rutas",
172-
link: "/es/key-concepts/controllers-routes",
180+
text: "Controladores y rutas",
181+
items: [
182+
{
183+
text: "Defición de Controladores",
184+
link: "/es/key-concepts/controllers/definition",
185+
},
186+
{
187+
text: "Implementación de Rutas",
188+
link: "/es/key-concepts/controllers/routes",
189+
},
190+
],
173191
},
174192
{
175193
text: "Manejo de Contexto y Peticiones",

docs/en/index.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
layout: home
3+
4+
hero:
5+
name: "Sword"
6+
text: "Rust Web Framework"
7+
tagline: Asynchronous, modular and ready to scale.
8+
image:
9+
src: /logo.png
10+
alt: Sword Logo
11+
actions:
12+
- theme: brand
13+
text: What is Sword?
14+
link: /en/introduction/
15+
- theme: alt
16+
text: Get Started
17+
link: /en/introduction/how-to-start.md
18+
- theme: alt
19+
text: GitHub
20+
link: "https://github.com/sword-web/"
21+
22+
features:
23+
- title: Asynchronous by default
24+
details:
25+
Built on Tokio, Sword is an asynchronous framework that relies on the
26+
well-known Tokio runtime to handle multiple concurrent connections efficiently.
27+
28+
- title: Module-based architecture
29+
details: Build server-side applications with a modular architecture, layer separation, and dependency injection.
30+
31+
- title: Integrated middlewares
32+
details: Includes integrated middlewares for CORS, Request Timeout, security headers, and more.
33+
---

docs/en/key-concepts/configuration/application.md

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -62,47 +62,3 @@ database_url = "${DATABASE_URL}" # Uses DATABASE_URL variable (required)
6262
```
6363

6464
The syntax is: `${VARIABLE_NAME:default_value}`. If you don't specify a default value and the variable doesn't exist, configuration loading will fail.
65-
66-
## Configuration Parameters
67-
68-
### `host`
69-
70-
- **Type**: String
71-
- **Default value**: `"0.0.0.0"`
72-
- **Description**: IP address or hostname where the server will bind. `0.0.0.0` means it will listen on all available network interfaces.
73-
74-
### `port`
75-
76-
- **Type**: Integer (u16)
77-
- **Default value**: `8080`
78-
- **Description**: Port number on which the server will listen for HTTP connections.
79-
80-
### `body_limit`
81-
82-
- **Type**: String
83-
- **No default value** (required)
84-
- **Description**: Maximum size allowed for request bodies. Useful for preventing denial-of-service (DoS) attacks. Valid examples: `"1MB"`, `"100KB"`, `"5GB"`.
85-
86-
### `request_timeout_seconds`
87-
88-
- **Type**: Integer (u64)
89-
- **Default value**: `null` (no timeout)
90-
- **Description**: Maximum time in seconds to wait for a request. If exceeded, the request will be automatically aborted.
91-
92-
### `graceful_shutdown`
93-
94-
- **Type**: Boolean
95-
- **Default value**: `false`
96-
- **Description**: If enabled, the server will allow in-flight requests to complete before shutting down when it receives a termination signal (such as Ctrl+C).
97-
98-
### `name`
99-
100-
- **Type**: String
101-
- **Default value**: `null` (optional)
102-
- **Description**: Application name. Displayed in startup logs.
103-
104-
### `environment`
105-
106-
- **Type**: String
107-
- **Default value**: `null` (optional)
108-
- **Description**: Environment name (e.g., "development", "production"). You can use this variable in your code to adapt your application's behavior based on the environment.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Defining Controllers
2+
3+
A controller is commonly known as a function that handles an HTTP request and returns an HTTP response. In Sword, we handle controllers as `structs`, and their methods are what actually handle the HTTP requests.
4+
5+
You'll notice this is a different approach from other Rust web frameworks, where controllers are functions. This object-oriented approach allows you to group related functionality within the same controller, making it easier to organize and maintain your code.
6+
7+
## Creating a Controller
8+
9+
To define a controller, you need to create a `struct` and mark it using the `#[controller]` macro.
10+
11+
```rust
12+
use sword::prelude::*;
13+
14+
#[controller("/api")]
15+
struct ApiController;
16+
17+
// ... assuming main function and other imports ...
18+
19+
Application::builder()
20+
.with_controller::<ApiController>()
21+
.build()
22+
```
23+
24+
### `#[controller]` Macro Attributes
25+
26+
#### `path`
27+
28+
The `path` attribute defines the route prefix for all routes within the controller. In the example above, all routes defined in `ApiController` will have the `/api` prefix.
29+
30+
### `version`
31+
32+
The `version` attribute allows you to define a version for the controller, which will be included in the route. For example:
33+
34+
```rust
35+
#[controller("/api", version = "v1")]
36+
struct ApiController;
37+
```
38+
39+
This is equivalent to defining the controller with the `/api/v1` prefix. However, it provides additional semantic meaning, indicating that this controller belongs to version 1 of your API.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Defining Routes in Controllers
2+
3+
In Sword, routes are defined within the implementation block of a controller. To do this, you use the `#[routes]` macro above the `impl` block.
4+
5+
```rust
6+
use sword::prelude::*;
7+
use serde_json::Value;
8+
9+
#[controller("/api")]
10+
struct ApiController;
11+
12+
#[routes]
13+
impl ApiController {
14+
#[get("/hello")]
15+
async fn hello(&self) -> HttpResponse {
16+
HttpResponse::Ok().message("Hello, world!")
17+
}
18+
}
19+
```
20+
21+
A controller can access the request context through the `ctx: Context` parameter:
22+
23+
```rust
24+
use sword::prelude::*;
25+
26+
#[controller("/api")]
27+
struct ApiController;
28+
29+
#[routes]
30+
impl ApiController {
31+
#[get("/hello/{name}")]
32+
async fn hello(&self, ctx: Context) -> HttpResult<HttpResponse> {
33+
let name: String = ctx.param("name")?;
34+
35+
Ok(HttpResponse::Ok().message(format!("Hello, {}!", name)))
36+
}
37+
}
38+
```
39+
40+
To learn about all the features of `Context`, see the [Request Context](../context-requests.md) section.
41+
42+
## Supported HTTP Methods
43+
44+
Currently, Sword supports the most common HTTP methods:
45+
46+
- `#[get("...")]`
47+
- `#[post("...")]`
48+
- `#[put("...")]`
49+
- `#[delete("...")]`
50+
- `#[patch("...")]`
51+
52+
### Route Syntax
53+
54+
Routes can include parameters, which are defined by enclosing the parameter name in curly braces `{}`. For example, in the route `/users/{id}`, `{id}` is a parameter that can be extracted from the request context.
55+
56+
For more details on route syntax, you can [check the axum documentation](https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.route).
57+
58+
## Using `async`
59+
60+
Sword is built on `axum`, which uses `tokio` as its async runtime. Therefore, all controller methods must be `async`, even if they don't perform any asynchronous operations within the method body.
61+
62+
## Using `&self`
63+
64+
As you may have noticed, controller methods receive `&self` as their first parameter. This allows controllers to inject dependencies through their fields. However, this topic will be covered in detail in the [Dependency Injection](../dependency-injection.md) section.

docs/es/key-concepts/configuration/application.md

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -62,47 +62,3 @@ database_url = "${DATABASE_URL}" # Usa la variable DATABASE_URL (required)
6262
```
6363

6464
La sintaxis es: `${VARIABLE_NAME:valor_por_defecto}`. Si no especificas un valor por defecto y la variable no existe, la carga fallará.
65-
66-
## Parámetros de configuración
67-
68-
### `host`
69-
70-
- **Tipo**: String
71-
- **Valor por defecto**: `"0.0.0.0"`
72-
- **Descripción**: Dirección IP o hostname donde se vinculará el servidor. `0.0.0.0` significa que escuchará en todas las interfaces de red disponibles.
73-
74-
### `port`
75-
76-
- **Tipo**: Integer (u16)
77-
- **Valor por defecto**: `8080`
78-
- **Descripción**: Puerto en el que escuchará el servidor para conexiones HTTP.
79-
80-
### `body_limit`
81-
82-
- **Tipo**: String
83-
- **Sin valor por defecto** (requerido)
84-
- **Descripción**: Tamaño máximo permitido para los cuerpos de las solicitudes. Útil para prevenir ataques de negación de servicio (DoS). Ejemplos válidos: `"1MB"`, `"100KB"`, `"5GB"`.
85-
86-
### `request_timeout_seconds`
87-
88-
- **Tipo**: Integer (u64)
89-
- **Valor por defecto**: `null` (sin timeout)
90-
- **Descripción**: Tiempo máximo en segundos que se espera a una solicitud. Si se excede, la solicitud será abortada automáticamente.
91-
92-
### `graceful_shutdown`
93-
94-
- **Tipo**: Boolean
95-
- **Valor por defecto**: `false`
96-
- **Descripción**: Si está habilitado, el servidor permitirá que las solicitudes en curso se completen antes de apagarse cuando reciba una señal de terminación (como Ctrl+C).
97-
98-
### `name`
99-
100-
- **Tipo**: String
101-
- **Valor por defecto**: `null` (opcional)
102-
- **Descripción**: Nombre de la aplicación. Se muestra en los logs de inicio.
103-
104-
### `environment`
105-
106-
- **Tipo**: String
107-
- **Valor por defecto**: `null` (opcional)
108-
- **Descripción**: Nombre del entorno (ej: "development", "production"). Puedes usar esta variable en tu código para adaptar el comportamiento de la aplicación.

docs/es/key-concepts/controllers-routes.md

Lines changed: 0 additions & 1 deletion
This file was deleted.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Definición de Controladores
2+
3+
Un controlador es comunmente conocido como una función que maneja una solicitud HTTP y devuelve una respuesta HTTP. En sword manejamos los controladores como `structs`, sus metodos son los que manejan las solicitudes HTTP.
4+
5+
Notarás que este es un enfoque diferente al de otros frameworks web en Rust, donde los controladores son funciones. Este enfoque orientado a objetos permite agrupar funcionalidades relacionadas dentro de un mismo controlador, facilitando la organización y el mantenimiento del código.
6+
7+
## Definiendo un Controlador
8+
9+
Para definir un controlador, debes crear un `struct` y luego marcarla utilizando la macro `#[controller]`.
10+
11+
```rust
12+
use sword::prelude::*;
13+
14+
#[controller("/api")]
15+
struct ApiController;
16+
17+
... asumiendo la función main y otras importaciones ...
18+
19+
Application::builder()
20+
.with_controller::<ApiController>()
21+
.build()
22+
23+
```
24+
25+
### Atributos de la Macro `#[controller]`
26+
27+
#### `path`
28+
29+
El atributo `path` define el prefijo de ruta para todas las rutas dentro del controlador. En el ejemplo anterior, todas las rutas definidas en `ApiController` tendrán el prefijo `/api`.
30+
31+
### `version`
32+
33+
El atributo `version` permite definir una versión para el controlador, que se incluirá en la ruta. Por ejemplo:
34+
35+
```rust
36+
#[controller("/api", version = "v1")]
37+
struct ApiController;
38+
```
39+
40+
Esto es equivalente a definir el controlador con el prefijo `/api/v1`. Sin embargo aporta semántica adicional, indicando que este controlador pertenece a la versión 1 de la API.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Definiendo rutas en controladores
2+
3+
En Sword, las rutas se definen dentro del bloque de implementación de un controlador. Para ello debes utilizar la macro `#[routes]` sobre este bloque `impl`.
4+
5+
```rust
6+
use sword::prelude::*;
7+
use serde_json::Value;
8+
9+
#[controller("/api")]
10+
struct ApiController;
11+
12+
#[routes]
13+
impl ApiController {
14+
#[get("/hello")]
15+
async fn hello(&self) -> HttpResponse {
16+
HttpResponse::Ok().message("Hello, world!")
17+
}
18+
}
19+
```
20+
21+
Un controlador puede tener acceso al contexto de la `request` mediante el parámetro `ctx: Context`
22+
23+
```rust
24+
use sword::prelude::*;
25+
26+
#[controller("/api")]
27+
struct ApiController;
28+
29+
#[routes]
30+
impl ApiController {
31+
#[get("/hello/{name}")]
32+
async fn hello(&self, ctx: Context) -> HttpResult<HttpResponse> {
33+
let name: String = ctx.param("name")?;
34+
35+
Ok(HttpResponse::Ok().message(format!("Hello, {}!", name)))
36+
}
37+
}
38+
```
39+
40+
Para conocer todas las funcionalidades de `Context`, ver [Contexto de la Request](../context-requests.md).
41+
42+
## Métodos HTTP soportados
43+
44+
De momento, sword soporta los metódos HTTP más comunes:
45+
46+
- `#[get("...")]`
47+
- `#[post("...")]`
48+
- `#[put("...")]`
49+
- `#[delete("...")]`
50+
- `#[patch("...")]`
51+
52+
### Sintaxis de las rutas
53+
54+
Las rutas pueden incluir parámetros, que se definen encerrando el nombre del parámetro entre llaves `{}`. Por ejemplo, en la ruta `/users/{id}`, `{id}` es un parámetro que puede ser extraído desde el contexto de la request.
55+
56+
Para más detalles sobre la sintaxis de las rutas, puedes [consultar la documentación de axum](https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.route)
57+
58+
## Uso de `async`
59+
60+
Sword está construido sobre `axum`, que utiliza `tokio` como runtime asíncrono. Por lo tanto, todos los métodos de los controladores deben ser `async`, incluso si no realizan operaciones asíncronas dentro del cuerpo del método.
61+
62+
## Uso de `&self`
63+
64+
Como te habrás percatado, los métodos de los controladores reciben `&self` como primer parámetro. Esto permite que los controladores puedan inyectar dependencias a través de sus campos. Sin embargo, este tema se abordará en detalle en la sección de [Inyección de Dependencias](../dependency-injection.md).

0 commit comments

Comments
 (0)