{"id":26512959,"url":"https://github.com/evandersondev/darto","last_synced_at":"2025-07-09T17:06:29.097Z","repository":{"id":282268053,"uuid":"947950998","full_name":"evandersondev/darto","owner":"evandersondev","description":"🐶 Darto is a microframework inspired by Express for building web applications in Dart. It offers a simple API with familiar middleware patterns that make it easy to get started with web development!","archived":false,"fork":false,"pushed_at":"2025-06-25T18:17:19.000Z","size":3310,"stargazers_count":14,"open_issues_count":1,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-25T19:27:04.051Z","etag":null,"topics":["api","backend","dart","express","fastify","framework","microframework","rest-api"],"latest_commit_sha":null,"homepage":"https://darto-docs.vercel.app/","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/evandersondev.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-03-13T14:03:42.000Z","updated_at":"2025-06-25T18:17:22.000Z","dependencies_parsed_at":"2025-04-01T17:26:30.134Z","dependency_job_id":"9e4eeb73-cbed-48be-b638-92e6082f7974","html_url":"https://github.com/evandersondev/darto","commit_stats":null,"previous_names":["evandersondev/darto"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/evandersondev/darto","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evandersondev%2Fdarto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evandersondev%2Fdarto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evandersondev%2Fdarto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evandersondev%2Fdarto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/evandersondev","download_url":"https://codeload.github.com/evandersondev/darto/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/evandersondev%2Fdarto/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264502146,"owners_count":23618555,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","backend","dart","express","fastify","framework","microframework","rest-api"],"created_at":"2025-03-21T04:19:12.641Z","updated_at":"2025-07-09T17:06:29.048Z","avatar_url":"https://github.com/evandersondev.png","language":"Dart","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"./assets/logo.png\" width=\"200px\" align=\"center\" alt=\"Darto logo\" /\u003e\n  \u003ch1 align=\"center\"\u003eDarto\u003c/h1\u003e\n  \u003cbr\u003e\n  \u003cp align=\"center\"\u003e\n  \u003ca href=\"https://darto-docs.vercel.app/\"\u003e🐶 Oficial Darto Documentation\u003c/a\u003e\n  \u003cbr/\u003e\n    Darto is a microframework inspired by \u003ca href=\"https://expressjs.com/\"\u003eExpress\u003c/a\u003e for building web applications in Dart. It offers a simple API with familiar middleware patterns that make it easy to get started with web development!\n  \u003c/p\u003e\n\u003c/p\u003e\n\n\u003cbr/\u003e\n\n### Support 💖\n\nIf you find Darto useful, please consider supporting its development 🌟[Buy Me a Coffee](https://buymeacoffee.com/evandersondev).🌟 Your support helps us improve the framework and make it even better!\n\n\u003cbr\u003e\n\u003cbr\u003e\n\n\u003e #### **Note:** If you want data persistence, you can use the 🍷[Dartonic](https://pub.dev/packages/dartonic) package. It is a simple Query Builder for Dart inspired by Drizzle to work with databases like MySQL, PostgreSQL, SQLite.\n\n\u003cbr/\u003e\n\n## Table of Contents 🗒️\n\n- [Installation 📦](#installation-📦)\n- [Basic Usage 🚀](#basic-usage-🚀)\n- [Route Parameters and Query Parameters 📝](#route-parameters-and-query-parameters-📝)\n- [Returning implicit responses](#returning-implicit-responses)\n- [Config static files](#config-static-files)\n- [Upload Files](#upload-files)\n- [Middleware Usage 🛠️](#middleware-usage-🛠️)\n- [Example Routes 📡](#example-routes-📡)\n- [Sub-Routes 🚦](#sub-routes-🚦)\n- [WebSocket Integration 🔌](#websocket-integration-🔌)\n- [Send email 📧](#send-email-📧)\n- [HTTP Methods 🌐](#http-methods-🌐)\n- [Template Engine Configuration 🎨](#template-engine-configuration-🎨)\n- [Response Methods 📤](#response-methods-📤)\n- [Main Features](#main-features)\n\n\u003cbr/\u003e\n\n---\n\n\u003cbr\u003e\n\n## Installation 📦\n\nRun the following command to install Darto:\n\n```bash\ndart pub add darto\n```\n\nor\n\nAdd the package to your `pubspec.yaml` file:\n\n```yaml\ndependencies:\n  darto: ^0.0.26\n```\n\nThen, run the following command:\n\n```bash\nflutter pub get\n```\n\n\u003cbr\u003e\n\n## Basic Usage 🚀\n\n```dart\nimport 'package:darto/darto.dart';\n\nvoid main() {\n  final app = Darto();\n\n  // Example route\n  app.get('/ping', (Request req, Response res) {\n    res.send('pong');\n  });\n\n  app.listen(3000);\n}\n```\n\n\u003cbr\u003e\n\n## Route Parameters and Query Parameters 📝\n\n```dart\nvoid main() {\n  final app = Darto();\n\n  // Example route with route parameters\n  app.get('/user/:id', (Request req, Response res) {\n    final id = req.params['id'];\n\n    res.send('User ID: $id');\n  });\n\n  // Example route with query parameters\n  app.get('/search?name=John\u0026age=20', (Request req, Response res) {\n    final name = req.query['name'];\n    final age = req.query['age'];\n\n    res.send('Name: $name, Age: $age');\n  });\n}\n```\n\n\u003cbr\u003e\n\n### Returning implicit responses\n\n```dart\nvoid main() {\n  final app = Darto();\n\n  app.get('/hello', (Request req, Response res) {\n    return 'Hello, World!';\n  });\n}\n```\n\n\u003cbr\u003e\n\n### Config static files\n\nTo upload files, you can use the class Upload. Here's an example:\n\n```dart\nvoid main() {\n  // Serve static files from the \"public\" folder (using default options)\n  // You can access the static files in browser using the following URL:\n  // http://localhost:3000/public/index.html\n  app.static('public');\n\n  // Or you can send  the file as a response\n  app.get('/images', (Request req, Response res) {\n    res.sendFile('public/image.png');\n  });\n}\n```\n\n\u003cbr\u003e\n\n### Upload Files\n\nTo upload files, you can use the class Upload. Here's an example:\n\n```dart\nvoid main() {\n  // Instance of Upload class and define the upload directory\n  final upload = Upload(join(Directory.current.path, 'uploads'));\n\n  // Route to handle file upload\n  app.post('/upload', upload.single('file'), (Request req, Response res) {\n    if (req.file != null) {\n      res.json(req.file);\n    } else {\n      res.status(BAD_REQUEST).json({'error': 'No file uploaded'});\n    }\n  });\n}\n```\n\n### Enable Cors\n\nTo enable CORS (Cross-Origin Resource Sharing), you can use `useCors` helper. Here's an example:\n\n```dart\nvoid main() {\n  final app = Darto();\n\n  app.useCors(\n    origin: [\n        'https://example.com',\n        'https://another-domain.org'\n      ]\n    );\n\n  // Allow specific methods and headers\n  app.useCors(\n    methods: ['GET', 'POST'],\n    headers: ['Content-Type', 'Authorization'],\n  );\n}\n```\n\n\u003cbr\u003e\n\n## Middleware Usage 🛠️\n\nDarto supports different types of middleware to handle various tasks throughout the request-response lifecycle.\n\n### Global Middleware\n\nGlobal middlewares are applied to all incoming requests. You can register a global middleware using the `use` method.\n\n```dart\nvoid main() {\n  final app = Darto();\n\n  // Global middleware to log incoming requests\n  app.use((Request req, Response res, Next next) {\n    print('📝 Request: ${req.method} ${req.originalUrl}');\n\n    next();\n  });\n\n  app.listen(3000, () {\n    print('🔹 Server is running at http://localhost:3000');\n  });\n}\n```\n\n### Error Middleware\n\nError middlewares are applied to all incoming requests. You can register a error middleware using the `use` method.\n\n```dart\nvoid main() {\n  final app = Darto();\n\n  app.timeout(5000);\n\n  // Error middleware to handle timeouts\n  app.use((Err err, Request req, Response res, Next next) {\n    if (req.timedOut \u0026\u0026 !res.finished) {\n      res.status(SERVICE_UNAVAILABLE).json({\n        'error': 'Request timed out or internal error occurred.',\n      });\n    } else {\n      next(err);\n    }\n  });\n}\n```\n\n\u003cbr\u003e\n\n### Route-Specific Middleware\n\nRoute-specific middlewares are applied to specific routes. You can pass a middleware as an optional parameter when defining a route.\n\n```dart\nvoid main() {\n  final app = Darto();\n\n  // Middleware specific to a route\n  app.use('/task/:id', (Request req, Response res, Next next) {\n    print('Request Type: ${req.method}');\n\n    next();\n  });\n\n  app.get('/task/:id', (Request req, Response res) {\n    final id = req.params['id'];\n\n    res.send({'task': id});\n  });\n\n  // You can use the middleware directly in the route definition\n  // Create a middleware function\n  logMiddleware(Request req, Response res, Next next) {\n    print('Request Type: ${req.method}');\n\n    next();\n  };\n\n  // Example route with middleware\n  app.get('/user/:id', logMiddleware, (Request req, Response res) {\n    final id = req.params['id'];\n\n    res.send({'user': id});\n  });\n\n  app.listen(3000, () {\n    print('🔹 Server is running at http://localhost:3000');\n  });\n}\n```\n\n\u003cbr\u003e\n\n## Example Routes 📡\n\n```dart\n// Route to get user information by ID\napp.get('/user/:id', (Request req, Response res) {\n  final id = req.params['id'];\n\n  res.send({'user': id});\n});\n\n// Route to redirect to an external site\napp.get('/go', (Request req, Response res) {\n  res.redirect('http://example.com');\n});\n\n// Route to get a body\napp.get('/file', (Request req, Response res) async {\n  final body = await req.body;\n\n  res.send(body);\n});\n```\n\n\u003cbr\u003e\n\n---\n\n## Sub-Routes 🚦\n\nDarto also supports the creation of sub-routes so you can better organize your application. By mounting a router on a specific path prefix, all the routes defined in the sub-router will be grouped under that prefix. This makes it easy to modularize your code and maintain clarity in your route definitions. For example, you can create an authentication router that handles all routes under `/auth`:\n\n```dart\nRouter authRouter() {\n  final router = Router();\n\n  router.get('/login', (Request req, Response res) {\n    res.send('Login page');\n  });\n\n  return router;\n}\n\nvoid main() {\n  final app = Darto();\n\n  // Mount the authRouter on the \"/auth\" prefix:\n  app.use('/auth', authRouter());\n}\n```\n\nThis enables clear separation of concerns and enhances the reusability of your routing logic. 🚀\n\n\u003cbr\u003e\n\n## WebSocket Integration 🔌\n\nDarto integrates with WebSockets to facilitate real-time communication in your applications. With WebSocket support, you can easily create interactive features like live chats, notifications, or interactive dashboards. The framework provides a simple API to handle WebSocket events:\n\n```dart\nimport 'package:darto/darto.dart';\n\nvoid main() {\n  final app = Darto();\n\n  // Initialize WebSocket server\n  final server = DartoWebsocket();\n\n  // Handle new WebSocket connections\n  server.on('connection', (DartoSocketChannel socket) {\n    socket.stream.listen((message) {\n      socket.sink.add('Echo: $message');\n    });\n  });\n\n  // Start the HTTP and WebSocket servers\n  app.listen(3000, () {\n    server.listen('0.0.0.0', 3001);\n    print('HTTP server running on http://localhost:3000');\n  });\n}\n```\n\n\u003cbr\u003e\n\n## Send email 📧\n\n```dart\n// Get instance of DartoMailer\n  final mailer = DartoMailer();\n\n  // Create a transporter instance\n  final transporter = mailer.createTransport(\n    host: 'sandbox.smtp.mailtrap.io',\n    port: 2525,\n    ssl: false,\n    auth: {\n      'username': 'seu-username',\n      'password': 'sua-password',\n    },\n  );\n\n  // Send an email using the transporter\n  app.post('/send-email', (Request req, Response res) async {\n    final success = await transporter.sendMail(\n      from: 'seu-email@gmail.com',\n      to: 'destinatario@exemplo.com',\n      subject: 'Teste de Email via Gmail',\n      html: '''\n        \u003ch1\u003eBem-vindo ao Darto Mailer!\u003c/h1\u003e\n        \u003cp\u003eEste é um email de teste usando Darto Mailer.\u003c/p\u003e\n      ''',\n    );\n\n    if (success) {\n      return res.json({'message': 'Email enviado com sucesso!'});\n    } else {\n      return res.status(500).json({'error': 'Falha ao enviar email'});\n    }\n  });\n```\n\n\u003cbr\u003e\n\n## Template Engine Configuration 🎨\n\nDarto supports server-side rendering using a template engine. By default, it integrates with the Mustache template engine. You can configure the engine globally in your application as shown below:\n\n```dart\nimport 'dart:io';\nimport 'package:path/path.dart';\nimport 'package:darto/darto.dart';\n\nvoid main() {\n  final app = Darto();\n\n  // Set the directory where your template files are located\n  app.set('views', join(Directory.current.path, 'lib', 'pages'));\n  // Specify the view engine extension (e.g., \"mustache\")\n  app.set('view engine', 'mustache');\n\n  // Define a route to render a template (without the extension)\n  app.get('/', (Request req, Response res) {\n    res.render('index', {\n      'title': 'Welcome to Server Side Rendering',\n      'header': 'Hello from Darto!',\n      'message': 'This demonstrates how to configure a template engine in Darto using Mustache.'\n    });\n  });\n\n  app.listen(3000, () {\n    print('HTTP server running on http://localhost:3000');\n  });\n}\n```\n\nCreate your template file at `lib/pages/index.mustache`:\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\" /\u003e\n    \u003ctitle\u003e{{title}}\u003c/title\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003ch1\u003e{{header}}\u003c/h1\u003e\n    \u003cp\u003e{{message}}\u003c/p\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n\u003cbr\u003e\n\n## HTTP Methods 🌐\n\nDarto supports the following HTTP methods:\n\n- **GET**\n  Retrieves data from the server.\n  - Example: `app.get('/users', (Request req, Response res) =\u003e res.send('Get users'));`\n- **POST**\n  Sends data to the server to create a new resource.\n  - Example: `app.post('/users', (Request req, Response res) =\u003e res.send('Create user'));`\n- **PUT**\n  Updates an existing resource on the server.\n  - Example: `app.put('/users/:id', (Request req, Response res) =\u003e res.send('Update user'));`\n- **DELETE**\n  Deletes a resource from the server.\n  - Example: `app.delete('/users/:id', (Request req, Response res) =\u003e res.send('Delete user'));`\n- **PATCH**\n  Updates a specific field of a resource on the server.\n  - Example: `app.patch('/users/:id', (Request req, Response res) =\u003e res.send('Update user'));`\n- **HEAD**\n  Retrieves the headers of a resource without the body.\n  - Example: `app.head('/users/:id', (Request req, Response res) =\u003e res.send('Get user'));`\n- **OPTIONS**\n  Retrieves the supported HTTP methods for a resource.\n  - Example: `app.options('/users/:id', (Request req, Response res) =\u003e res.send('Get user'));`\n- **TRACE**\n  Performs a message loop-back test along the path to the resource.\n  - Example: `app.trace('/users/:id', (Request req, Response res) =\u003e res.send('Get user'));`\n\n\u003cbr\u003e\n\n## Response Methods 📤\n\nDarto provides several methods to control the response sent to the client:\n\n- **send**\n  Sends a response with the specified data.\n  - Example: `res.send('Hello, World!');`\n- **json**\n  Sends a JSON response with the specified data.\n  - Example: `res.json({'message': 'Hello, World!'});`\n- **end**\n  Ends the response and sends it to the client.\n  - Example: `res.end();`\n  - Example: `res.end('Hello, World!');`\n- **status**\n  Sets the HTTP status code for the response.\n  - Example: `res.status(200).send('OK');`\n- **redirect**\n  Redirects the client to a new URL.\n  - Example: `res.redirect('https://example.com');`\n- **download**\n  Initiates a file download by specifying the file path and optional options.\n  - Example: `res.download('path/to/file.txt', { filename: 'custom-filename.txt' });`\n- **sendFile**\n  Sends a file as a response.\n  - Example: `res.sendFile('path/to/file.txt');`\n- **error**\n  Sends an error response with the specified error message.\n  - Example: `res.error('An error occurred.');`\n- **cookie**\n  Sets a cookie in the response.\n  - Example: `res.cookie('cookieName', 'cookieValue');`\n- **clearCookie**\n  Clears a cookie from the response.\n  - Example: `res.clearCookie('cookieName');`\n- **render**\n  Renders a template with the specified data and sends it as a response.\n  - Example: `res.render('template', { data: 'Hello, World!' });`\n\n\u003cbr\u003e\n\n## Main Features\n\n- **Middlewares**  \n  Easily apply both global and route-specific middlewares to process requests, manage authentication, logging, data manipulation, and more.\n\n- **File Uploads**  \n  Supports file uploads natively using the `Upload` class, allowing the seamless handling and storage of files sent by clients.\n\n- **File Downloads**  \n  With the `download` method, you can send files as attachments, specify custom file names, and set up error callbacks for a controlled download experience.\n\n- **Static File Serving**  \n  Serve static files from designated directories using the `static` method, making folders (e.g., \"public\") accessible directly via URL.\n\n- **Send Files (sendFile)**  \n  Automatically handles the correct Content-Type based on file extensions to ensure files such as HTML, CSS, JavaScript, images, PDFs, etc., are served with the proper headers.\n\n- **Flexible Routing**  \n  Define routes with dynamic parameters (e.g., `/user/:id`) similar to Express.js, allowing easy extraction of parameters for RESTful API design.\n\n- **Sub-Routes**\n  Organize your routes into sub-routes for better modularity and maintainability.\n\n- **CORS and Custom Headers**  \n  Configure CORS and set custom HTTP headers to adhere to security policies and enhance communication.\n\n- **Input Sanitization and Basic Security**  \n  Incorporates input sanitization mechanisms along with basic protections to avoid injection attacks and mitigate denial-of-service (DoS) scenarios.\n\n- **WebSocket Support**\n  Integrates WebSocket support to facilitate real-time communication and interactive features in your applications.\n\n- **Error Handling**\n  Implement robust error handling mechanisms to gracefully manage errors and provide meaningful feedback to users.\n\n- **Template Engine Integration**\n  Integrate popular template engines Mustache to create dynamic and interactive web pages.\n\n\u003cbr\u003e\n\n---\n\nMade by evendersondev with ❤️ for Dart/Flutter developers! 🎯\n","funding_links":["https://buymeacoffee.com/evandersondev"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fevandersondev%2Fdarto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fevandersondev%2Fdarto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fevandersondev%2Fdarto/lists"}