=============== LIBRARY RULES =============== From library maintainers: - Always use file-based routing under the app/ directory - Route handlers must be named after HTTP methods (Get, Post, Put, Delete, etc.) - Use fuego.Context for handling requests and responses - Middleware functions must accept and return fuego.HandlerFunc - Proxy functions must return *fuego.ProxyResult - Page templates must use templ syntax with the Page() component - Layout templates must accept children... parameter - Use fuego generate commands for scaffolding new routes, middleware, pages, and proxies - Always run golangci-lint before committing to avoid CI failures - For deferred operations, use: defer func() { _ = file.Close() }() ### Install Fuego CLI Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Instructions for installing the Fuego CLI using Homebrew on macOS/Linux or directly using Go. This is the initial step to start using Fuego. ```bash brew install abdul-hamid-achik/tap/fuego-cli ``` ```bash go install github.com/abdul-hamid-achik/fuego/cmd/fuego@latest ``` -------------------------------- ### Start Fuego Application Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx This Go code snippet demonstrates the basic entry point for a Fuego application. It initializes a new Fuego app instance and starts the server on port 8080. Ensure the 'github.com/abdul-hamid-achik/fuego/pkg/fuego' package is available. ```go package main import ( "log" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func main() { app := fuego.New() log.Println("Starting server on :8080") if err := app.Start(":8080"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### API Middleware Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Demonstrates how to implement and apply middleware to API routes that are prefixed with `/api/*`. ```APIDOC ## API Middleware ### Description Applies custom middleware to all API routes under the `/api/` path. ### Method (Applies to all HTTP methods for routes under `/api/*`) ### Endpoint /api/* ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (All routes under /api/*) - The `X-API-Version: 1.0` header is automatically added to all responses for routes matching `/api/*`. #### Response Example (Headers are demonstrated in the `curl` command examples in the source text, showing the added header.) ``` -------------------------------- ### Tailwind CSS Setup and Build Commands (CSS/Bash) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx Configures Tailwind CSS with custom component classes and provides commands for building production-ready or development-watch modes. Requires Tailwind CSS to be installed. ```css /* styles/input.css */ @import "tailwindcss"; /* Custom components */ .btn-primary { @apply inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-orange-600 hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500; } .btn-secondary { @apply inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50; } .input { @apply block w-full rounded-md border-gray-300 shadow-sm focus:border-orange-500 focus:ring-orange-500 sm:text-sm; } ``` ```bash fuego tailwind build # For production (minified) fuego tailwind watch # For development ``` -------------------------------- ### Go Fuego Application Setup and Server Start Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/app.mdx This Go code demonstrates how to initialize a Fuego web application, apply global middleware, configure static file serving, define API routes, and implement graceful shutdown. It includes dependencies on the 'fuego' package and standard Go libraries for context, logging, and signal handling. The server starts listening on port 3000. ```go package main import ( "context" "log" "os" "os/signal" "syscall" "time" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func main() { app := fuego.New( fuego.WithAppDir("app"), fuego.WithStaticDir("static"), ) // Global middleware app.Use(fuego.Logger()) app.Use(fuego.Recover()) app.Use(fuego.RequestID()) app.Use(fuego.CORS()) // Serve static files app.Static("/static", "static") // API routes app.Group("/api", func(api *fuego.RouteGroup) { api.Get("/health", func(c *fuego.Context) error { return c.JSON(200, map[string]string{"status": "ok"}) }) }) // Graceful shutdown go func() { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) <-sigChan ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := app.Shutdown(ctx); err != nil { log.Fatal("Shutdown error:", err) } }() // Start server log.Println("Starting server on :3000") if err := app.Listen(":3000"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Core Application Setup in Go Source: https://context7.com/abdul-hamid-achik/fuego/llms.txt Demonstrates how to create and configure a Fuego application instance. This includes setting up the logger, adding global middleware, serving static files, and starting the server. The framework automatically scans the 'app/' directory for routes. ```go package main import ( "log" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func main() { // Create new Fuego application with default configuration app := fuego.New() // Request logging is enabled by default! // Customize the logger with advanced configuration app.SetLogger(fuego.RequestLoggerConfig{ Compact: true, // Next.js-style compact format ShowTimestamp: true, // Show [HH:MM:SS] timestamp ShowSize: true, // Show response size (1.2KB) ShowIP: false, // Show client IP SkipStatic: true, // Skip logging static files Level: fuego.LogLevelInfo, // info, warn, error, debug, off }) // Add global middleware (applies to all routes) app.Use(fuego.Recover()) app.Use(fuego.RequestID()) // Serve static files from the "static" directory at /static URL prefix app.Static("/static", "static") // Start server on port 3000 with graceful shutdown // Automatically scans app/ directory for routes log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### Fuego CLI Upgrade Output Example Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/cli.mdx Example output when running the `fuego upgrade` command, showing current and latest versions, download progress, verification, extraction, installation status, backup information for rollback, and release notes. ```bash Fuego Upgrade Current version: v0.4.3 Latest version: v0.5.0 (released 2 days ago) -> Downloading fuego_0.5.0_darwin_arm64.tar.gz... -> Verifying checksum... -> Extracting binary... -> Installing... OK Upgraded successfully to v0.5.0! Backup saved to: ~/.cache/fuego/fuego.backup To rollback: fuego upgrade --rollback Release notes: - Added self-update command - Improved route generation performance - Fixed issue with nested layouts ``` -------------------------------- ### Create and Navigate Fuego Project Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Commands to create a new Fuego project named 'myapp' and navigate into its directory. This sets up the basic file structure for a new application. ```bash fuego new myapp cd myapp ``` -------------------------------- ### Basic Fuego Application Example Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/overview.mdx A simple Go program demonstrating how to create a Fuego application, add middleware (Logger and Recover), define a root route handler that returns JSON, and start the HTTP server. This example illustrates the fundamental structure of a Fuego application. ```go package main import "github.com/abdul-hamid-achik/fuego/pkg/fuego" func main() { app := fuego.New() app.Use(fuego.Logger()) app.Use(fuego.Recover()) app.Get("/", func(c *fuego.Context) error { return c.JSON(200, map[string]string{"message": "Hello, World!"}) }) app.Listen(":3000") } ``` -------------------------------- ### Load and Use Fuego Configuration in Go Source: https://context7.com/abdul-hamid-achik/fuego/llms.txt This Go code demonstrates how to load configuration from a `fuego.yaml` file using the Fuego library. It shows the process of initializing the Fuego application with custom configuration, accessing configuration values like port and application directory, validating the configuration, ensuring the application directory exists, and starting the application listener. It relies on the `fuego` package for configuration loading and application setup. ```go package main import ( "log" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func main() { // Load configuration from fuego.yaml config, err := fuego.LoadConfig(".") if err != nil { log.Fatal(err) } // Create app with custom configuration app := fuego.New(fuego.WithConfig(config)) // Access configuration values port := config.Port appDir := config.AppDir // Validate configuration if err := config.Validate(); err != nil { log.Fatal(err) } // Ensure app directory exists if err := config.EnsureAppDir(); err != nil { log.Fatal(err) } app.Listen(config.ListenAddress()) } ``` -------------------------------- ### Fuego CLI: Generating Pages (Bash) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/core-concepts/templates.mdx Provides examples of using the Fuego CLI to generate new pages within a project. Commands demonstrate creating a basic page, a page with a layout, and a nested page structure. ```bash # Basic page fuego generate page dashboard # Page with layout fuego generate page admin/settings --with-layout # Nested page fuego generate page users/profile ``` -------------------------------- ### Full Example: Task Dashboard with HTMX (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/core-concepts/templates.mdx A comprehensive example of a Fuego dashboard page integrating HTMX for a dynamic task list and form submission. It includes a `TaskList` div for displaying tasks and an `AddTaskForm` for adding new ones, both powered by HTMX attributes. ```go // app/dashboard/page.templ package dashboard templ Page() {

Dashboard

Tasks

Loading tasks...
} ``` -------------------------------- ### Example Configurations Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/config.mdx Example configurations for different environments. ```APIDOC ## Example Configurations ### Development ```go app := fuego.New( fuego.WithDev(true), fuego.WithPort("3000"), ) app.SetLogger(fuego.RequestLoggerConfig{ Level: fuego.LogLevelDebug, ShowIP: true, ShowUserAgent: true, }) ``` ### Production ```go app := fuego.New( fuego.WithHost("0.0.0.0"), fuego.WithPort(os.Getenv("PORT")), ) app.SetLogger(fuego.RequestLoggerConfig{ Level: fuego.LogLevelWarn, ShowIP: true, SkipPaths: []string{"/health"}, SkipStatic: true, }) ``` ### Testing ```go app := fuego.New( fuego.WithDev(false), ) app.DisableLogger() // No logging during tests ``` ``` -------------------------------- ### Using Components in a Page (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/core-concepts/templates.mdx Illustrates how to import and utilize custom components within another Fuego page. This example imports a `components` package and uses the `Card` and `Button` components to build a dashboard layout. ```go package dashboard import "myapp/app/_components" templ Page() {
@components.Card("Statistics") {

Your stats here

} @components.Button("Save", "primary")
} ``` -------------------------------- ### Fuego Quick Example - Users API (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/introduction.mdx Illustrates how to define GET and POST handlers for the /api/users route using Fuego's file-based routing. It shows context binding for POST requests and JSON responses for both. ```go // app/api/users/route.go package users import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // GET /api/users func Get(c *fuego.Context) error { return c.JSON(200, map[string]any{ "users": []string{"alice", "bob"}, }) } // POST /api/users func Post(c *fuego.Context) error { var input struct { Name string `json:"name"` } if err := c.Bind(&input); err != nil { return fuego.BadRequest("invalid input") } return c.JSON(201, map[string]string{"created": input.Name}) } ``` -------------------------------- ### API Middleware Example (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx An API-specific middleware that applies to routes under '/api/*'. It adds an API version header and tracks the response time of API requests, providing insights into performance. ```go // app/api/middleware.go package api import ( "time" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) // Middleware applies to all routes under /api/*. func Middleware() fuego.MiddlewareFunc { return func(next fuego.HandlerFunc) fuego.HandlerFunc { return func(c *fuego.Context) error { // Add API version header c.SetHeader("X-API-Version", "1.0.0") // Track response time start := time.Now() err := next(c) c.SetHeader("X-Response-Time", time.Since(start).String()) return err } } } ``` -------------------------------- ### Example: Testing Logger Configuration Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/config.mdx An example demonstrating how to disable the logger for testing purposes. This ensures that tests are not cluttered with log output. ```go app := fuego.New( fuego.WithDev(false), ) app.DisableLogger() // No logging during tests ``` -------------------------------- ### Bash cURL Examples for Testing Middleware Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx Provides cURL commands to test the implemented authentication and authorization middleware. Examples include accessing public, protected, and admin routes with valid and invalid tokens, demonstrating unauthorized and forbidden responses. ```bash # Public route - no auth needed curl http://localhost:8080/api/public # Protected route - requires valid token curl http://localhost:8080/api/protected \ -H "Authorization: Bearer valid-user-token" # Admin route - requires admin role curl http://localhost:8080/api/admin \ -H "Authorization: Bearer valid-admin-token" # Unauthorized request curl http://localhost:8080/api/protected # Returns: {"error":"unauthorized","message":"Authorization header required"} ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/advanced/configuration.mdx Example `fuego.yaml` file demonstrating server, directory, development, and middleware configurations. This file allows for extensive customization of Fuego application behavior. ```yaml # Server configuration port: 3000 host: 0.0.0.0 # Directory configuration app_dir: app static_dir: static static_path: /static # Development configuration dev: hot_reload: true watch_extensions: - .go - .templ exclude_dirs: - node_modules - .git - _* # Middleware configuration middleware: logger: true recover: true ``` -------------------------------- ### Templating with Additional Props (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/core-concepts/templates.mdx Demonstrates how to define a Fuego page component that accepts additional parameters beyond URL parameters. Non-URL parameters will have zero values unless explicitly fetched. This example shows a User struct and a Page component rendering user details or a loading message. ```go package id type User struct { ID string Name string Email string } templ Page(id string, user User) {
if user.Name != "" {

{ user.Name }

{ user.Email }

} else {

Loading user { id }...

}
} ``` -------------------------------- ### Example: Development Logger Configuration Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/config.mdx An example of configuring the request logger for a development environment. It enables debug logging and includes client IP and User-Agent information. ```go app := fuego.New( fuego.WithDev(true), fuego.WithPort("3000"), ) app.SetLogger(fuego.RequestLoggerConfig{ Level: fuego.LogLevelDebug, ShowIP: true, ShowUserAgent: true, }) ``` -------------------------------- ### Example Authentication Middleware for Fuego Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/middleware/overview.mdx This Go code provides a complete example of an authentication middleware for the Fuego framework. It checks for the 'Authorization' header and validates a hardcoded token. If valid, it sets 'user_id' and 'user_role' in the context. It returns a `fuego.MiddlewareFunc`. ```go // app/api/protected/middleware.go package protected import "github.com/abdul-hamid-achik/fuego/pkg/fuego" func Middleware() fuego.MiddlewareFunc { return func(next fuego.HandlerFunc) fuego.HandlerFunc { return func(c *fuego.Context) error { token := c.Header("Authorization") if token == "" { return c.JSON(401, map[string]string{ "error": "unauthorized", "message": "Authorization header required", }) } // In a real app, validate the JWT token here if token != "Bearer valid-token" { return c.JSON(403, map[string]string{ "error": "forbidden", "message": "Invalid token", }) } // Add user info to context c.Set("user_id", "user-123") c.Set("user_role", "admin") return next(c) } } } ``` -------------------------------- ### Example: Production Logger Configuration Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/config.mdx An example of configuring the request logger for a production environment. It sets the log level to Warn, includes IP addresses, and skips specific paths and static files. ```go app := fuego.New( fuego.WithHost("0.0.0.0"), fuego.WithPort(os.Getenv("PORT")), ) app.SetLogger(fuego.RequestLoggerConfig{ Level: fuego.LogLevelWarn, ShowIP: true, SkipPaths: []string{"/health"}, SkipStatic: true, }) ``` -------------------------------- ### Proxy Testing with cURL Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx Provides examples of how to test the proxy functionality using cURL commands. It covers normal requests, handling legacy URLs, accessing admin routes with and without authentication, and testing rate limiting. The output includes expected responses or status codes. ```bash # Normal request curl http://localhost:8080/api/users # Response headers include X-Request-ID, X-Proxy-Time # Legacy URL (gets rewritten) curl http://localhost:8080/v1/users # Response headers include X-Deprecated: true # Admin route without auth curl http://localhost:8080/api/admin # Returns: 401 Unauthorized # Admin route with auth curl http://localhost:8080/api/admin \ -H "Authorization: Bearer admin-secret" # Returns: 200 OK # Rate limiting (run 101+ times quickly) for i in {1..105}; do curl -s http://localhost:8080/api/users; done # After 100 requests: 429 Too Many Requests ``` -------------------------------- ### Global Middleware Example (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx A global middleware function that applies to all routes in the Fuego application. It sets essential security headers such as 'X-Content-Type-Options', 'X-Frame-Options', and 'X-XSS-Protection' for enhanced security. ```go // app/middleware.go package app import ( "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) // Middleware applies to ALL routes in the app. func Middleware() fuego.MiddlewareFunc { return func(next fuego.HandlerFunc) fuego.HandlerFunc { return func(c *fuego.Context) error { // Add security headers to all responses c.SetHeader("X-Content-Type-Options", "nosniff") c.SetHeader("X-Frame-Options", "DENY") c.SetHeader("X-XSS-Protection", "1; mode=block") return next(c) } } } ``` -------------------------------- ### Bash API Testing Commands for User Operations Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx Provides `curl` commands to test the user API endpoints. Includes examples for health checks, creating users with JSON data, and listing all users. Assumes the API is running on localhost:8080. ```bash # Health check curl http://localhost:8080/api/health # Create users curl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"name": "Alice", "email": "alice@example.com"}' # List users curl http://localhost:8080/api/users ``` -------------------------------- ### Test API Endpoints with cURL Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Example cURL commands to test the GET and POST API routes for users. These commands demonstrate how to fetch data and send data to create a new resource. ```bash # List users curl http://localhost:3000/api/users # Create a user curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name":"Charlie"}' ``` -------------------------------- ### Health Check API Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx The `route.go` file in `app/api/health/` automatically maps to the `GET /api/health` endpoint for health checks. ```APIDOC ## GET /api/health ### Description Provides a health check endpoint for the application. ### Method GET ### Endpoint /api/health ### Parameters #### Path Parameters None #### Query Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - Details of the response are not explicitly defined in the provided text, but typically indicate a successful health check. #### Response Example (Example not provided in source text) ``` -------------------------------- ### Core Application Setup Source: https://context7.com/abdul-hamid-achik/fuego/llms.txt Demonstrates how to create and configure a Fuego application instance, including setting up logging and middleware. ```APIDOC ## Core Application Setup ### Description Creating and configuring a Fuego application instance, including request logging and global middleware. ### Method N/A (Application Initialization) ### Endpoint N/A (Application Initialization) ### Parameters #### Query Parameters N/A #### Request Body N/A ### Request Example ```go package main import ( "log" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func main() { // Create new Fuego application with default configuration app := fuego.New() // Customize the logger with advanced configuration app.SetLogger(fuego.RequestLoggerConfig{ Compact: true, ShowTimestamp: true, ShowSize: true, ShowIP: false, SkipStatic: true, Level: fuego.LogLevelInfo, }) // Add global middleware app.Use(fuego.Recover()) app.Use(fuego.RequestID()) // Serve static files app.Static("/static", "static") // Start server on port 3000 log.Fatal(app.Listen(":3000")) } ``` ### Response #### Success Response (200) N/A (Application initialization does not return a direct response). #### Response Example N/A ``` -------------------------------- ### Add API Route for Users (GET, POST) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Go code to define handlers for GET and POST requests to the /api/users endpoint. The GET handler returns a list of users, while the POST handler creates a new user based on the request body. ```go package users import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // GET /api/users func Get(c *fuego.Context) error { users := []map[string]any{ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, } return c.JSON(200, users) } // POST /api/users func Post(c *fuego.Context) error { var user struct { Name string `json:"name"` } if err := c.Bind(&user); err != nil { return fuego.BadRequest("invalid request body") } return c.JSON(201, map[string]any{ "id": 3, "name": user.Name, }) } ``` -------------------------------- ### Add Dynamic API Routes for Users by ID (GET, PUT, DELETE) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Go code for dynamic API routes to handle GET, PUT, and DELETE requests for individual users based on their ID. It demonstrates how to access route parameters and bind request bodies. ```go package users import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // GET /api/users/:id func Get(c *fuego.Context) error { id := c.Param("id") return c.JSON(200, map[string]any{ "id": id, "name": "User " + id, }) } // PUT /api/users/:id func Put(c *fuego.Context) error { id := c.Param("id") var input struct { Name string `json:"name"` } if err := c.Bind(&input); err != nil { return fuego.BadRequest("invalid request body") } return c.JSON(200, map[string]any{ "id": id, "name": input.Name, "updated": true, }) } // DELETE /api/users/:id func Delete(c *fuego.Context) error { id := c.Param("id") return c.JSON(200, map[string]string{ "message": "User " + id + " deleted", }) } ``` -------------------------------- ### GET /api/tasks Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx Retrieves the list of tasks and renders them as HTML, suitable for HTMX. ```APIDOC ## GET /api/tasks ### Description Returns task list as HTML for HTMX. ### Method GET ### Endpoint /api/tasks ### Parameters #### Query Parameters #### Request Body ### Request Example ### Response #### Success Response (200) - **HTML** (string) - HTML representation of the task list. #### Response Example ```html ``` ``` -------------------------------- ### Go: Application Setup with Fuego and Database Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/database.mdx This Go code sets up the main application, connecting to the database, running migrations, and initializing the Fuego web framework. It also includes a graceful shutdown mechanism to ensure the database connection is closed properly. ```go // main.go package main import ( "context" "log" "os" "os/signal" "syscall" "myapp/internal/database" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func main() { // Connect to database if err := database.Connect(); err != nil { log.Fatal("failed to connect to database:", err) } defer database.Close() // Run migrations if err := database.Migrate(); err != nil { log.Fatal("failed to run migrations:", err) } // Create Fuego app app := fuego.New() // Graceful shutdown ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancel() go func() { <-ctx.Done() log.Println("shutting down...") database.Close() os.Exit(0) }() // Start server if err := app.Start(":8080"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### User CRUD Operations Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx Endpoints for listing, creating, getting, updating, and deleting users. ```APIDOC ## GET /api/users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /api/users ### Parameters ### Request Body None ### Request Example None ### Response #### Success Response (200) - **users** (array) - A list of user objects. - **count** (integer) - The total number of users returned. #### Response Example ```json { "users": [ { "id": 1, "name": "Alice", "email": "alice@example.com", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ], "count": 1 } ``` ``` ```APIDOC ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "Alice", "email": "alice@example.com" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier of the created user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **created_at** (string) - The timestamp when the user was created. - **updated_at** (string) - The timestamp when the user was last updated. #### Response Example ```json { "id": 1, "name": "Alice", "email": "alice@example.com", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ``` ```APIDOC ## GET /api/users/{id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user. ### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **created_at** (string) - The timestamp when the user was created. - **updated_at** (string) - The timestamp when the user was last updated. #### Response Example ```json { "id": 1, "name": "Alice", "email": "alice@example.com", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` #### Error Response (404) - **error** (string) - "user not found" ``` ```APIDOC ## PUT /api/users/{id} ### Description Updates an existing user's information. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to update. #### Request Body - **name** (string) - Optional - The new name for the user. - **email** (string) - Optional - The new email address for the user. ### Request Example ```json { "name": "Alice Smith", "email": "alice.smith@example.com" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the updated user. - **name** (string) - The updated name of the user. - **email** (string) - The updated email address of the user. - **created_at** (string) - The timestamp when the user was created. - **updated_at** (string) - The timestamp when the user was last updated. #### Response Example ```json { "id": 1, "name": "Alice Smith", "email": "alice.smith@example.com", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:05:00Z" } ``` #### Error Response (404) - **error** (string) - "user not found" ``` ```APIDOC ## DELETE /api/users/{id} ### Description Deletes a user by their ID. ### Method DELETE ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to delete. ### Request Body None ### Request Example None ### Response #### Success Response (204) No content. #### Error Response (404) - **error** (string) - "user not found" ``` -------------------------------- ### sqlc Installation and Configuration for PostgreSQL Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/database.mdx This snippet details the installation of the sqlc command-line tool using Go's package manager and provides a sample configuration file (sqlc.yaml) for generating Go code from PostgreSQL SQL queries. It specifies the database engine, query and schema locations, and output directory, along with generation options for Go code. ```bash go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest ``` ```yaml # sqlc.yaml version: "2" sql: - engine: "postgresql" queries: "internal/database/queries/" schema: "internal/database/schema/" gen: go: package: "db" out: "internal/database/db" sql_package: "pgx/v5" emit_json_tags: true emit_prepared_queries: true emit_interface: true ``` -------------------------------- ### Handle Optional Catch-All Documentation Routes in Go Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/guides/examples.mdx This Go code demonstrates an optional catch-all route in Fuego for API documentation. It uses `[[...path]]` to match URLs like `/api/docs` (where path is empty) or `/api/docs/getting-started` (where path is `getting-started`). The function retrieves documentation content based on the path parameter. ```go // app/api/docs/[[...path]]/route.go package docs import ( "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) // Documentation structure var docs = map[string]string{ "": "Welcome to the API documentation", "getting-started": "Getting started guide", "api/users": "Users API reference", "api/posts": "Posts API reference", "api/authentication": "Authentication guide", } // GET /api/docs/[[...path]] - Optional catch-all for documentation // Matches: // /api/docs → path = "" // /api/docs/getting-started → path = "getting-started" // /api/docs/api/users → path = "api/users" func Get(c *fuego.Context) error { path := c.Param("path") content, ok := docs[path] if !ok { return c.JSON(404, map[string]string{ "error": "documentation not found", "path": path, }) } return c.JSON(200, map[string]any{ "path": path, "content": content, "sections": getDocSections(), }) } func getDocSections() []string { sections := make([]string, 0, len(docs)) for k := range docs { if k != "" { sections = append(sections, k) } } return sections } ``` -------------------------------- ### Fuego Route Handler Example Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/cli.mdx Example Go code demonstrating handler functions for different HTTP methods (GET, PUT, DELETE) for a dynamic route. It shows how to access route parameters and bind request bodies. ```go // app/api/users/[id]/route.go package users import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // Get handles GET /api/users/:id func Get(c *fuego.Context) error { id := c.Param("id") return c.JSON(200, map[string]any{ "id": id, }) } // Put handles PUT /api/users/:id func Put(c *fuego.Context) error { id := c.Param("id") var body map[string]any if err := c.Bind(&body); err != nil { return c.JSON(400, map[string]string{"error": "invalid body"}) } return c.JSON(200, map[string]any{ "id": id, "updated": true, }) } // Delete handles DELETE /api/users/:id func Delete(c *fuego.Context) error { id := c.Param("id") return c.JSON(200, map[string]string{ "message": "deleted " + id, }) } ``` -------------------------------- ### Go API Route Example Source: https://github.com/abdul-hamid-achik/fuego/blob/main/README.md Defines API endpoints using Go functions based on file structure. This example shows how to handle GET and POST requests for '/api/users'. It utilizes the 'fuego' context for binding input and sending JSON responses. ```go package users import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // GET /api/users func Get(c *fuego.Context) error { return c.JSON(200, map[string]any{ "users": []string{"alice", "bob"}, }) } // POST /api/users func Post(c *fuego.Context) error { var input struct { Name string `json:"name"` } if err := c.Bind(&input); err != nil { return fuego.BadRequest("invalid input") } return c.JSON(201, map[string]string{"created": input.Name}) } ``` -------------------------------- ### Initialize Fuego App with Multiple Options (Go) Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/config.mdx Demonstrates initializing a Fuego application with multiple configuration options passed as variadic arguments to `fuego.New()`. This allows for consolidated configuration at app startup. ```go app := fuego.New( fuego.WithAppDir("routes"), fuego.WithStaticDir("public"), fuego.WithPort("8080"), fuego.WithHost("127.0.0.1"), fuego.WithDev(true), ) ``` -------------------------------- ### Applying BasicAuth Middleware in Go Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/middleware/overview.mdx Shows how to implement basic authentication in Go using Fuego's `fuego.BasicAuth()` middleware. The example includes a function that verifies a username and password, demonstrating a simple authentication mechanism. ```go app.Use(fuego.BasicAuth(func(user, pass string) bool { return user == "admin" && pass == "secret" })) ``` -------------------------------- ### Create Fuego App Instance Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/app.mdx Demonstrates how to create a new Fuego application instance. Supports creating an app with default settings or providing custom options like specifying application and static directories. The `fuego.New()` function is used for instantiation. ```go import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // Basic app with defaults app := fuego.New() // App with options app := fuego.New( fuego.WithAppDir("routes"), fuego.WithStaticDir("public"), ) ``` -------------------------------- ### Start MCP Server with Fuego CLI Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/cli.mdx Command to start an MCP (Model Context Protocol) server for AI assistant integration. It accepts a working directory flag. This setup allows AI assistants to interact with Fuego projects using natural language commands. ```bash fuego mcp serve [flags] ``` -------------------------------- ### User Management API Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Defines API routes for managing users, including listing, creating, retrieving, updating, and deleting users. ```APIDOC ## User Management API ### Description API endpoints for managing user resources. ### Method (Varies per endpoint: GET, POST, PUT, DELETE) ### Endpoint /api/users /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for a user. #### Query Parameters None #### Request Body - **Name** (string) - Required (for POST and PUT) - The name of the user. ### Request Example **POST /api/users:** ```json { "name": "Charlie" } ``` **PUT /api/users/{id}:** ```json { "name": "Updated Name" } ``` ### Response #### Success Response (200) - **GET /api/users**: Returns a list of users. Example: `[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]` - **GET /api/users/{id}**: Returns details of a specific user. Example: `{"id": "123", "name": "User 123"}` - **PUT /api/users/{id}**: Returns confirmation of update. Example: `{"id": "123", "name": "Updated Name", "updated": true}` - **DELETE /api/users/{id}**: Returns a success message. Example: `{"message": "User 123 deleted"}` #### Success Response (201) for POST /api/users - Returns the created user with an assigned ID. Example: `{"id": 3, "name": "Charlie"}` #### Error Response - **POST /api/users**: Returns a 400 Bad Request if the request body is invalid. Example: `{"error": "invalid request body"}` #### Response Example **GET /api/users:** ```json [ { "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" } ] ``` **POST /api/users:** ```json { "id": 3, "name": "Charlie" } ``` **GET /api/users/123:** ```json { "id": "123", "name": "User 123" } ``` **PUT /api/users/123:** ```json { "id": "123", "name": "Updated Name", "updated": true } ``` **DELETE /api/users/123:** ```json { "message": "User 123 deleted" } ``` ``` -------------------------------- ### Build Fuego Application for Production Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Commands to build the Fuego application for production and run the compiled binary. This process creates a single, self-contained executable. ```bash fuego build ./myapp ``` -------------------------------- ### Implement API Middleware Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/getting-started/quickstart.mdx Go code for a Fuego middleware that sets the 'X-API-Version' header to '1.0' for all routes under '/api/*'. This is useful for consistent API responses. ```go package api import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // Middleware applies to all routes under /api/* func Middleware() fuego.MiddlewareFunc { return func(next fuego.HandlerFunc) fuego.HandlerFunc { return func(c *fuego.Context) error { c.SetHeader("X-API-Version", "1.0") return next(c) } } } ``` -------------------------------- ### Go Dynamic Route Example Source: https://github.com/abdul-hamid-achik/fuego/blob/main/README.md Demonstrates how to create dynamic routes in Go using Fuego. The file `app/api/users/[id]/route.go` maps to routes like `/api/users/:id`. The example shows how to extract URL parameters using `c.Param("id")`. ```go package users import "github.com/abdul-hamid-achik/fuego/pkg/fuego" // GET /api/users/:id func Get(c *fuego.Context) error { id := c.Param("id") return c.JSON(200, map[string]any{ "id": id, "name": "User " + id, }) } ``` -------------------------------- ### Examples of Fuego CLI Upgrade Command Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/cli.mdx Demonstrates various ways to use the `fuego upgrade` command, including upgrading to the latest stable version, checking for updates without installing, installing a specific version, including prereleases, forcing a reinstall, rolling back, and obtaining JSON output for scripting. ```bash # Upgrade to latest stable version fuego upgrade # Check for updates without installing fuego upgrade --check # Install a specific version fuego upgrade --version v0.5.0 # Include prereleases fuego upgrade --prerelease # Force reinstall current version fuego upgrade --force # Rollback to previous version fuego upgrade --rollback # JSON output for scripting fuego upgrade --json ``` -------------------------------- ### File-Based API Middleware Example in Go Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/middleware/overview.mdx Illustrates creating file-based middleware for specific API routes in Go. This example demonstrates adding an API version header and tracking response time for requests within the `/api/*` path. It utilizes the `fuego.MiddlewareFunc` type and standard Go packages. ```go package api import ( "time" "github.com/abdul-hamid-achik/fuego/pkg/fuego" ) func Middleware() fuego.MiddlewareFunc { return func(next fuego.HandlerFunc) fuego.HandlerFunc { return func(c *fuego.Context) error { // Add API version header c.SetHeader("X-API-Version", "1.0") // Track timing start := time.Now() err := next(c) c.SetHeader("X-Response-Time", time.Since(start).String()) return err } } } ``` -------------------------------- ### Get Tailwind CSS Info with Fuego CLI Source: https://github.com/abdul-hamid-achik/fuego/blob/main/docs/api/cli.mdx Displays information about the Tailwind CSS installation, including version and binary path. Can output information in JSON format. ```bash # Default info fuego tailwind info # JSON output fuego tailwind info --json ```