### Run Echonext Todo API Example Source: https://github.com/abdussamadbello/echonext/blob/master/examples/quickstart/README.md Commands to run the Echonext Todo API example from the repository root or the example directory. The server starts on http://localhost:8080. ```bash # From the repository root go run example/main.go # Or from this directory go run ../../example/main.go ``` -------------------------------- ### Run Quickstart Todo API Example Source: https://github.com/abdussamadbello/echonext/blob/master/examples/README.md A complete, runnable Todo API demonstrating all EchoNext features. This example is suitable for beginners to understand the integration of different components. It requires Go to be installed and the EchoNext CLI. ```bash # From repository root go run example/main.go # Visit http://localhost:8080/api/docs ``` -------------------------------- ### Project Setup using CLI Source: https://github.com/abdussamadbello/echonext/blob/master/docs/guides/api-development.md Guides users through setting up a new EchoNext project using the command-line interface. It covers project initialization, domain generation, database setup, and running the API server. Assumes Go and EchoNext CLI are installed. ```bash # Create new project echonext init myapi --module=github.com/username/myapi cd myapi # Generate your first domain echonext generate domain user # Initialize database echonext db init # Run the API go mod tidy go run ./cmd/api ``` -------------------------------- ### Quick Start: Initialize and Generate Todo API Source: https://github.com/abdussamadbello/echonext/blob/master/examples/todo-api/README.md These commands show the initial setup for creating a new Todo API project using EchoNext, including domain generation and database initialization. ```bash echonext init todo-api echonext generate domain todo echonext db init ``` -------------------------------- ### Bash Command to Run Quickstart Example Source: https://github.com/abdussamadbello/echonext/blob/master/README.md Command to run the EchoNext quickstart example project. This allows users to quickly test the application and access its documentation at http://localhost:8080/api/docs. ```bash go run example/main.go # Visit http://localhost:8080/api/docs ``` -------------------------------- ### Running the Echonext Quickstart Source: https://github.com/abdussamadbello/echonext/blob/master/docs/examples/README.md Provides instructions on how to run the Echonext quickstart example. This involves cloning the repository, navigating to the directory, and executing the main Go file. ```bash git clone https://github.com/abdussamadbello/echonext cd echonext go run example/main.go ``` -------------------------------- ### Prerequisites for Echonext Examples Source: https://github.com/abdussamadbello/echonext/blob/master/docs/examples/README.md Lists the prerequisites for running Echonext examples, including installing Go version 1.24 or later, the Echonext package itself, and optionally the Echonext CLI. It provides commands for installation. ```bash # Install Go 1.24+ go version # Install EchoNext go get github.com/abdussamadbello/echonext # Install CLI (optional but recommended) go install github.com/abdussamadbello/echonext/cmd/echonext-cli@latest ``` -------------------------------- ### Add EchoNext to Existing Project Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Integrates EchoNext into an existing Go project by first fetching the library and then creating a basic 'main.go' file to initialize and run an EchoNext application. This demonstrates how to manually add EchoNext if not starting with the CLI. ```bash # In your existing project directory go get github.com/abdussamadbello/echonext # Create a basic main.go cat > main.go << 'EOF' package main import ( "github.com/abdussamadbello/echonext" ) func main() { app := echonext.New() app.SetInfo("My API", "1.0.0", "My EchoNext API") app.GET("/health", func(c echo.Context) error { return c.JSON(200, map[string]string{"status": "ok"}) }) app.Start(":8080") } EOF # Run it go run main.go ``` -------------------------------- ### Install EchoNext Library Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Adds the core EchoNext library to your Go project's dependencies using the 'go get' command. This command fetches the specified package and its dependencies, updating your go.mod and go.sum files. ```bash go get github.com/abdussamadbello/echonext ``` -------------------------------- ### Initialize EchoNext Project and Install Dependencies Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/quickstart.md This snippet shows the bash commands to create a new project directory, initialize a Go module, and install the EchoNext library. It sets up the basic environment for building an API. ```bash mkdir todo-api && cd todo-api go mod init github.com/yourusername/todo-api go get github.com/abdussamadbello/echonext ``` -------------------------------- ### Quick Start: EchoNext Go API Setup Source: https://github.com/abdussamadbello/echonext/blob/master/README.md This Go code demonstrates a basic EchoNext application setup. It defines request and response structures with validation tags, registers typed routes for user creation and retrieval, configures OpenAPI and Swagger UI serving, and starts the Echo server. It requires the 'echonext' and 'echo' Go packages. ```go package main import ( "github.com/abdussamadbello/echonext" "github.com/labstack/echo/v4" ) // Define your request/response types type CreateUserRequest struct { Name string `json:"name" validate:"required,min=2" Email string `json:"email" validate:"required,email" } type UserResponse struct { ID string `json:"id" Name string `json:"name" Email string `json:"email" } func main() { // Create new EchoNext app app := echonext.New() // Set API info app.SetInfo("User API", "1.0.0", "User management service") // Register typed routes app.POST("/users", createUser, echonext.Route{ Summary: "Create a new user", Description: "Creates a new user with the provided information", Tags: []string{"Users"}, }) app.GET("/users/:id", getUser, echonext.Route{ Summary: "Get user by ID", Tags: []string{"Users"}, }) // Serve OpenAPI spec and Swagger UI app.ServeOpenAPISpec("/api/openapi.json") app.ServeSwaggerUI("/api/docs", "/api/openapi.json") // Start server app.Start(":8080") } // Handlers with typed parameters func createUser(c echo.Context, req CreateUserRequest) (UserResponse, error) { // Your business logic here user := UserResponse{ ID: "123", Name: req.Name, Email: req.Email, } return user, nil } func getUser(c echo.Context) (UserResponse, error) { id := c.Param("id") // Fetch user logic return UserResponse{ ID: id, Name: "John Doe", Email: "john@example.com", }, nil } ``` -------------------------------- ### Install golangci-lint Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs golangci-lint, a powerful Go code linter that aggregates multiple linters into one. This command fetches and installs the latest version, making it available in your PATH for code quality checks. ```bash go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest ``` -------------------------------- ### Running the Todo API Example Source: https://github.com/abdussamadbello/echonext/blob/master/examples/todo-api/README.md Instructions for running the Todo List API, including dependency installation, running with Docker, or locally with a PostgreSQL database. ```bash # 1. Install dependencies go mod tidy # 2. Run with Docker (includes PostgreSQL) docker-compose up # Or run locally (requires PostgreSQL) # Update configs/development.yaml with your DB connection go run ./cmd/api # 3. Visit API docs open http://localhost:8080/api/docs ``` -------------------------------- ### Install EchoNext CLI Tool Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs the EchoNext CLI tool using 'go install', ensuring you have the latest version. This command compiles and installs the 'echonext-cli' package, making the executable available in your Go bin path. ```bash go install github.com/abdussamadbello/echonext/cmd/echonext-cli@latest ``` -------------------------------- ### EchoNext CLI Installation and Usage Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/quickstart.md Provides commands for installing and using the EchoNext Command Line Interface (CLI). The CLI simplifies project creation, domain generation, database initialization, and running the API. ```bash # Install CLI go install github.com/abdussamadbello/echonext/cmd/echonext-cli@latest # Create a new project echonext init todo-api --module=github.com/yourusername/todo-api # Navigate to project cd todo-api # Generate a domain (model, service, handler, DTOs) echonext generate domain todo # Initialize database echonext db init # Run the API go mod tidy go run ./cmd/api ``` -------------------------------- ### Example Projects Source: https://github.com/abdussamadbello/echonext/blob/master/README.md Provides links to various example projects demonstrating different levels of EchoNext framework usage, from quickstart to advanced microservices. ```APIDOC ## 🎓 Example Projects Learn by example! Check out our complete example projects: ### [⚡ Quickstart](example/main.go) - Running Example Complete working Todo API. Run it now! ```bash go run example/main.go # Visit http://localhost:8080/api/docs ``` ### [📝 Todo List API](examples/todo-api/) - Beginner Simple CRUD operations demonstrating the basics of EchoNext. ```bash echonext init todo-api echonext generate domain todo go run ./cmd/api ``` ### [📰 Blog API](examples/blog-api/) - Intermediate Multi-domain blog platform with authentication, search, and relationships. ```bash echonext init blog-api echonext generate domain post echonext generate domain comment echonext generate domain user ``` ### [🛒 E-commerce API](examples/ecommerce-api/) - Advanced Complete e-commerce platform with orders, payments, and inventory. ```bash echonext init ecommerce-api echonext generate domain product echonext generate domain order echonext generate domain payment ``` ### [🔧 Microservices](examples/microservice/) - Expert Distributed system with service-to-service communication and events. See [examples/README.md](examples/README.md) for detailed guides and more examples. ``` -------------------------------- ### Verify EchoNext Installation with a Test Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Creates and runs a simple Go test file to verify that the EchoNext application can be initialized successfully. This test checks if 'echonext.New()' returns a valid application instance. ```go // test.go package main import ( "testing" "github.com/abdussamadbello/echonext" ) func TestEchoNext(t *testing.T) { app := echonext.New() if app == nil { t.Fatal("Failed to create EchoNext app") } } ``` ```bash go test test.go ``` -------------------------------- ### Install Configuration and File Watching Packages Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs Viper for configuration management and fsnotify for file system event watching. These are common dependencies for building robust applications that handle configuration changes dynamically. ```bash go get github.com/spf13/viper go get github.com/fsnotify/fsnotify ``` -------------------------------- ### Install Database Helper Packages Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs GORM and a specific database driver (e.g., PostgreSQL) for use with EchoNext's database contribution packages. These packages provide ORM capabilities and database connectivity. ```bash go get gorm.io/gorm go get gorm.io/driver/postgres # or driver/mysql, driver/sqlite, etc. ``` -------------------------------- ### Todo API Endpoints Source: https://github.com/abdussamadbello/echonext/blob/master/examples/quickstart/README.md This section details the available endpoints for interacting with the Todo API. ```APIDOC ## POST /todos ### Description Creates a new todo item. ### Method POST ### Endpoint /todos ### Request Body - **title** (string) - Required - The title of the todo item. - **description** (string) - Optional - A detailed description of the todo item. - **priority** (string) - Optional - The priority level of the todo item (e.g., "high", "medium", "low"). ### Request Example ```json { "title": "Buy groceries", "description": "Milk, eggs, bread", "priority": "high" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the created todo. - **title** (string) - The title of the todo item. - **description** (string) - The description of the todo item. - **priority** (string) - The priority level of the todo item. - **createdAt** (string) - The timestamp when the todo was created. - **updatedAt** (string) - The timestamp when the todo was last updated. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "title": "Buy groceries", "description": "Milk, eggs, bread", "priority": "high", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z" } ``` ``` ```APIDOC ## GET /todos/:id ### Description Retrieves a specific todo item by its ID. ### Method GET ### Endpoint /todos/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the todo item to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the todo. - **title** (string) - The title of the todo item. - **description** (string) - The description of the todo item. - **priority** (string) - The priority level of the todo item. - **createdAt** (string) - The timestamp when the todo was created. - **updatedAt** (string) - The timestamp when the todo was last updated. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "title": "Buy groceries", "description": "Milk, eggs, bread", "priority": "high", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z" } ``` ``` ```APIDOC ## GET /todos ### Description Lists all todo items with optional pagination. ### Method GET ### Endpoint /todos ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **limit** (integer) - Optional - The number of items per page. Defaults to 10. ### Response #### Success Response (200) - **todos** (array) - An array of todo items. - Each item has the following structure: - **id** (string) - The unique identifier for the todo. - **title** (string) - The title of the todo item. - **description** (string) - The description of the todo item. - **priority** (string) - The priority level of the todo item. - **createdAt** (string) - The timestamp when the todo was created. - **updatedAt** (string) - The timestamp when the todo was last updated. - **total** (integer) - The total number of todo items. - **page** (integer) - The current page number. - **limit** (integer) - The number of items per page. #### Response Example ```json { "todos": [ { "id": "123e4567-e89b-12d3-a456-426614174000", "title": "Buy groceries", "description": "Milk, eggs, bread", "priority": "high", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z" } ], "total": 1, "page": 1, "limit": 10 } ``` ``` ```APIDOC ## PUT /todos/:id ### Description Updates an existing todo item by its ID. ### Method PUT ### Endpoint /todos/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the todo item to update. ### Request Body - **title** (string) - Optional - The new title of the todo item. - **description** (string) - Optional - The new description of the todo item. - **priority** (string) - Optional - The new priority level of the todo item. ### Request Example ```json { "description": "Milk, eggs, bread, and butter" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the todo. - **title** (string) - The title of the todo item. - **description** (string) - The description of the todo item. - **priority** (string) - The priority level of the todo item. - **createdAt** (string) - The timestamp when the todo was created. - **updatedAt** (string) - The timestamp when the todo was last updated. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "title": "Buy groceries", "description": "Milk, eggs, bread, and butter", "priority": "high", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:05:00Z" } ``` ``` ```APIDOC ## DELETE /todos/:id ### Description Deletes a todo item by its ID. ### Method DELETE ### Endpoint /todos/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the todo item to delete. ### Response #### Success Response (204) No Content. ``` ```APIDOC ## GET /api/docs ### Description Serves the Swagger UI for interactive API documentation. ### Method GET ### Endpoint /api/docs ``` ```APIDOC ## GET /api/openapi.json ### Description Provides the OpenAPI specification for the API in JSON format. ### Method GET ### Endpoint /api/openapi.json ``` -------------------------------- ### Bash Commands for Blog API Example Source: https://github.com/abdussamadbello/echonext/blob/master/README.md Commands to initialize and generate domains for the Blog API example project. This intermediate example showcases multi-domain setup with authentication and search. ```bash echonext init blog-api echonext generate domain post echonext generate domain comment echonext generate domain user ``` -------------------------------- ### Manual Project Setup and Configuration Source: https://github.com/abdussamadbello/echonext/blob/master/docs/guides/api-development.md Demonstrates manual setup of an EchoNext API application in Go. It covers database initialization using GORM with PostgreSQL, app configuration, adding essential middleware (Logger, Recover, CORS), registering domain handlers, and serving OpenAPI/Swagger documentation. Requires Go, EchoNext, and GORM libraries. ```go package main import ( "log" "github.com/abdussamadbello/echonext" "github.com/abdussamadbello/echonext/pkg/contrib/database" "github.com/abdussamadbello/echonext/pkg/middleware" "gorm.io/driver/postgres" "your_project_path/domain/user" ) func main() { // Initialize database db, err := database.Connect( postgres.Open("postgres://user:pass@localhost/dbname"), database.DefaultConfig(), ) if err != nil { log.Fatal(err) } // Create app app := echonext.New() app.SetInfo("My API", "1.0.0", "Production API") // Add middleware app.Use(middleware.Logger()) app.Use(middleware.Recover()) app.Use(middleware.CORS()) // Register domains userHandler := user.NewHandler(user.NewService(db)) userHandler.Register(app) // Serve OpenAPI docs app.ServeOpenAPISpec("/api/openapi.json") app.ServeSwaggerUI("/api/docs", "/api/openapi.json") // Start server app.Start(":8080") } ``` -------------------------------- ### Project Initialization and Workflows Source: https://github.com/abdussamadbello/echonext/blob/master/docs/cli/overview.md Guides for starting new projects and common development workflows. ```APIDOC ## Starting a New Project ### Description This workflow outlines the steps to initialize a new Echonext project from scratch. ### Steps 1. **Create project:** Use `echonext init` to create the project directory and module. ```bash echonext init myapp --module=github.com/user/myapp cd myapp ``` 2. **Generate domains:** Use `echonext generate domain` for core entities. ```bash echonext generate domain user echonext generate domain product echonext generate domain order ``` 3. **Setup database:** Initialize the database migration system. ```bash echonext db init ``` 4. **Run:** Install dependencies and start the API. ```bash go mod tidy go run ./cmd/api ``` ``` ```APIDOC ## Adding a New Feature ### Description This workflow covers the process of adding a new feature, focusing on domain generation, schema updates, and migrations. ### Steps 1. **Generate domain:** Create the necessary files for the new feature's domain. ```bash echonext generate domain comment ``` 2. **Customize generated files:** Modify the domain files to define the feature's specifics: * Edit `domain/comment/model.go` for the database schema. * Edit `domain/comment/service.go` for business logic. * Edit `domain/comment/handler.go` for API endpoints. * Edit `domain/comment/dto.go` for request/response types. 3. **Run migrations:** Apply the schema changes to the database. ```bash echonext db migrate ``` 4. **Test:** Run the API to test the new feature. ```bash go run ./cmd/api ``` ``` ```APIDOC ## Adding Middleware ### Description This workflow details how to generate and implement custom middleware in your Echonext application. ### Steps 1. **Generate middleware:** Use the CLI to create the middleware boilerplate. ```bash echonext generate middleware auth ``` 2. **Edit middleware file:** Implement the desired logic within the generated file (e.g., `internal/middleware/auth.go`). 3. **Use in application:** Integrate the middleware into your main application setup. ```go // In your main.go or app setup file: // app.Use(middleware.Auth()) ``` ``` ```APIDOC ## Adding OpenTelemetry ### Description This workflow explains how to generate OpenTelemetry setup code and configure your application for distributed tracing and metrics. ### Steps 1. **Generate OTEL setup:** Use the CLI to generate the necessary OpenTelemetry integration code. ```bash echonext generate otel ``` 2. **Configure environment variables:** Set the required environment variables for OpenTelemetry. ```bash export OTEL_SERVICE_NAME="myapp" export OTEL_EXPORTER_OTLP_ENDPOINT="localhost:4317" ``` 3. **Use in application:** Initialize and apply the OpenTelemetry middleware in your main application setup. ```go // In your main.go or app setup file: // import "path/to/your/otel" // import "path/to/your/middleware" // ctx := context.Background() // shutdown := otel.MustInit(ctx, otel.DefaultConfig()) // defer shutdown() // app.Use(middleware.OTELMiddleware("myapp")) ``` ``` -------------------------------- ### Complete Handler Example in Go Source: https://github.com/abdussamadbello/echonext/blob/master/docs/examples/README.md A comprehensive example of a Go handler for managing users in an Echonext application. It demonstrates registering POST, GET, PUT, and DELETE routes for user resources and includes basic error handling. Dependencies include 'echonext' and 'echo'. ```go package user import ( "github.com/abdussamadbello/echonext" "github.com/labstack/echo/v4" ) type Handler struct { service *Service } func NewHandler(service *Service) *Handler { return &Handler{service: service} } func (h *Handler) Register(app *echonext.App) { app.POST("/users", h.Create, echonext.Route{ Summary: "Create user", Tags: []string{"Users"}, SuccessStatus: 201, }) app.GET("/users/:id", h.Get, echonext.Route{ Summary: "Get user by ID", Tags: []string{"Users"}, }) app.PUT("/users/:id", h.Update, echonext.Route{ Summary: "Update user", Tags: []string{"Users"}, }) app.DELETE("/users/:id", h.Delete, echonext.Route{ Summary: "Delete user", Tags: []string{"Users"}, SuccessStatus: 204, }) } func (h *Handler) Create(c echo.Context, req CreateUserRequest) (UserResponse, error) { user, err := h.service.Create(req) if err != nil { return UserResponse{}, echo.NewHTTPError(500, err.Error()) } return ToUserResponse(user), nil } func (h *Handler) Get(c echo.Context) (UserResponse, error) { id := parseID(c.Param("id")) user, err := h.service.GetByID(id) if err != nil { return UserResponse{}, echo.NewHTTPError(404, "user not found") } return ToUserResponse(user), nil } ``` -------------------------------- ### Initialize New EchoNext Project Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Creates a new EchoNext project named 'myapp' with the specified module path. This command uses the EchoNext CLI to scaffold a new project, including necessary files and configurations. ```bash # Create a new project echonext init myapp --module=github.com/yourusername/myapp # Navigate to the project cd myapp # Install dependencies go mod tidy # Run the application go run ./cmd/api ``` -------------------------------- ### Example: Get All Todo Items Source: https://github.com/abdussamadbello/echonext/blob/master/examples/todo-api/README.md This curl command shows how to retrieve a list of all todo items by sending a GET request to the `/todos` endpoint. ```bash curl http://localhost:8080/todos ``` -------------------------------- ### Install golang-migrate CLI Source: https://github.com/abdussamadbello/echonext/blob/master/docs/guides/deployment.md Installs the golang-migrate command-line interface tool, specifically with support for PostgreSQL databases. This tool is used for managing and applying database migrations. ```bash # Install migrate CLI go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest ``` -------------------------------- ### Production-Ready Echonext Application in Go Source: https://context7.com/abdussamadbello/echonext/llms.txt A complete Go application example using Echonext, demonstrating configuration loading, database integration, OpenTelemetry setup, API routing, middleware, and graceful shutdown. This example is production-ready and includes common features. ```go package main import ( "context" "log" "os" "os/signal" "syscall" "time" "github.com/abdussamadbello/echonext" "github.com/abdussamadbello/echonext/pkg/contrib/config" "github.com/abdussamadbello/echonext/pkg/contrib/database" "github.com/abdussamadbello/echonext/pkg/contrib/middleware" "github.com/labstack/echo/v4/middleware" "gorm.io/driver/postgres" ) type AppConfig struct { Server ServerConfig `mapstructure:"server"` Database DatabaseConfig `mapstructure:"database"` OTEL OTELConfig `mapstructure:"otel"` } func main() { // Load configuration var cfg AppConfig if err := config.LoadSimple(&cfg); err != nil { log.Fatalf("Failed to load config: %v", err) } // Initialize database dbCfg := database.DefaultConfig() db, err := database.Connect( postgres.Open(cfg.Database.DSN()), dbCfg, ) if err != nil { log.Fatalf("Failed to connect to database: %v", err) } defer database.Close(db) // Initialize OTEL ctx := context.Background() shutdown, err := middleware.InitOTEL(ctx, middleware.OTELConfig{ ServiceName: "production-api", ServiceVersion: "1.0.0", Environment: cfg.OTEL.Environment, Endpoint: cfg.OTEL.Endpoint, EnableTracing: true, EnableMetrics: true, }) if err != nil { log.Printf("OTEL initialization failed: %v", err) } else { defer shutdown.Shutdown(ctx) } // Create application app := echonext.New() // Configure API metadata app.SetInfo("Production API", "1.0.0", "Production-ready REST API") app.SetServers([]echonext.Server{ {URL: "https://api.prod.com", Description: "Production"}, }) app.AddSecurityScheme("bearerAuth", echonext.Security{ Type: "bearer", Scheme: "JWT", }) // Global middleware app.Use(middleware.Logger()) app.Use(middleware.Recover()) app.Use(middleware.RequestID()) app.Use(middleware.OTELMiddleware("production-api")) app.Use(middleware.RateLimiter(middleware.NewRateLimiterMemoryStore(100))) // Setup routes setupRoutes(app, db) // Serve documentation app.ServeOpenAPISpec("/api/openapi.json") app.ServeSwaggerUI("/api/docs", "/api/openapi.json") // Start server with graceful shutdown go func() { if err := app.Start(":" + cfg.Server.Port); err != nil { log.Fatalf("Server error: %v", err) } }() // Wait for interrupt signal quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt, syscall.SIGTERM) <-quit // Graceful shutdown shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := app.Shutdown(shutdownCtx); err != nil { log.Fatalf("Server shutdown error: %v", err) } log.Println("Server gracefully stopped") } func setupRoutes(app *echonext.App, db *gorm.DB) { // Health check app.GET("/health", healthCheck, echonext.Route{ Summary: "Health check", Tags: []string{"System"}, }) // API v1 v1 := app.Group("/api/v1") v1.Use(middleware.JWT([]byte(os.Getenv("JWT_SECRET")))) // User endpoints users := v1.Group("/users") users.POST("", createUser, echonext.Route{ Summary: "Create user", SuccessStatus: 201, Tags: []string{"Users"}, }) users.GET("", listUsers, echonext.Route{ Summary: "List users", Tags: []string{"Users"}, }) users.GET("/:id", getUser, echonext.Route{ Summary: "Get user", Tags: []string{"Users"}, }) users.PUT("/:id", updateUser, echonext.Route{ Summary: "Update user", Tags: []string{"Users"}, }) users.DELETE("/:id", deleteUser, echonext.Route{ Summary: "Delete user", SuccessStatus: 204, Tags: []string{"Users"}, }) } ``` -------------------------------- ### Run Application with Air Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Starts the application using Air, enabling hot reloading. When you save changes to your Go files, Air will automatically rebuild and restart the application. ```bash air ``` -------------------------------- ### Install Air for Hot Reload Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs the Air tool, a live-reloading development server for Go applications. This command fetches and installs the latest version of Air, making it available in your PATH. ```bash go install github.com/air-verse/air@latest ``` -------------------------------- ### Initialize Microservices with EchoNext CLI Source: https://github.com/abdussamadbello/echonext/blob/master/examples/README.md Steps to initialize multiple microservices using EchoNext CLI. This example demonstrates setting up services for an event-driven architecture with inter-service communication. It requires the EchoNext CLI and Go. ```bash # Initialize services echonext init user-service --module=github.com/yourusername/user-service echonext init order-service --module=github.com/yourusername/order-service echonext init notification-service --module=github.com/yourusername/notification-service # Each service follows the same pattern cd user-service echonext generate domain user echonext db init ``` -------------------------------- ### Install EchoNext CLI (Windows) Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs the EchoNext command-line interface tool on Windows using PowerShell. This command downloads and executes an installation script that places the 'echonext' binary in the user's local bin directory and updates the PATH. ```powershell iwr -useb https://raw.githubusercontent.com/abdussamadbello/echonext/master/install.ps1 | iex ``` -------------------------------- ### Bash Commands for Microservices Example Source: https://github.com/abdussamadbello/echonext/blob/master/README.md Instructions to set up the Microservices example project. This expert-level example focuses on building distributed systems with inter-service communication and event handling. ```bash echonext init microservice # Further commands would follow for specific service setup ``` -------------------------------- ### Install EchoNext CLI (Linux/macOS) Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Installs the EchoNext command-line interface tool on Linux or macOS using a curl script. This command downloads and executes an installation script that places the 'echonext' binary in the user's local bin directory and updates the PATH. ```bash curl -sSL https://raw.githubusercontent.com/abdussamadbello/echonext/master/install.sh | bash ``` -------------------------------- ### Add Go Bin to PATH Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Appends the Go binary directory (determined by `go env GOPATH`) to your system's PATH environment variable. This is required if you installed the EchoNext CLI using `go install` and the command is not recognized. ```bash export PATH=$PATH:$(go env GOPATH)/bin ``` -------------------------------- ### Add ~/.local/bin to PATH (Linux/macOS) Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Appends the `~/.local/bin` directory to your system's PATH environment variable on Linux or macOS. This is necessary if the EchoNext CLI was installed there and the 'echonext' command is not found. ```bash # Linux/macOS export PATH="$PATH:$HOME/.local/bin" ``` -------------------------------- ### Initialize and Generate EchoNext Blog API Project Source: https://github.com/abdussamadbello/echonext/blob/master/examples/blog-api/README.md This Bash script demonstrates the initialization of a new EchoNext project for a blog API and the generation of necessary domains (posts, comments, users, categories) and middleware (auth, ratelimit). It also includes commands for database setup and running the application. ```bash # Initialize echonext init blog-api --module=github.com/yourusername/blog-api cd blog-api # Generate domains echonext generate domain post echonext generate domain comment echonext generate domain user echonext generate domain category # Generate middleware echonext generate middleware auth echonext generate middleware ratelimit # Setup database echonext db init # Run go mod tidy go run ./cmd/api ``` -------------------------------- ### Run Example Todo API Source: https://github.com/abdussamadbello/echonext/blob/master/README.md Instructions to run the example Todo API application. This command executes the main Go file for the example, making the API server accessible locally. ```bash go run example/main.go ``` -------------------------------- ### Run golangci-lint Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Executes golangci-lint to analyze your Go project for potential issues and enforce code quality standards. This command runs the linter against your current directory. ```bash golangci-lint run ``` -------------------------------- ### Run and Test EchoNext API Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/quickstart.md These commands demonstrate how to manage dependencies, run the Go application, and interact with the API using cURL. It includes steps for listing, creating, retrieving, updating, and deleting todos, as well as accessing the Swagger UI for interactive testing. ```bash # Install dependencies go mod tidy # Run the server go run main.go # List all todos curl http://localhost:8080/todos # Create a todo curl -X POST http://localhost:8080/todos \ -H "Content-Type: application/json" \ -d '{"title": "My new todo"}' # Get a specific todo curl http://localhost:8080/todos/1 # Update a todo curl -X PUT http://localhost:8080/todos/1 \ -H "Content-Type: application/json" \ -d '{"completed": true}' # Delete a todo curl -X DELETE http://localhost:8080/todos/1 ``` -------------------------------- ### Initialize Go Module Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Initializes a new Go module in your project directory. This command creates a `go.mod` file, which is essential for managing dependencies in Go projects, especially when encountering 'package not found' errors. ```bash go mod init github.com/yourusername/yourproject ``` -------------------------------- ### Setup GraphQL API with gqlgen in Go Source: https://context7.com/abdussamadbello/echonext/llms.txt Demonstrates setting up a GraphQL API using gqlgen with EchoNext, including automatic context passing and playground support. It covers schema creation, configuration of GraphQL handler, and accessing Echo context within resolvers. Supports WebSocket subscriptions for real-time updates. ```go import ( "context" "errors" "github.com/abdussamadbello/echonext" "github.com/abdussamadbello/echonext/graphql" "github.com/99designs/gqlgen/graphql/handler" "github.com/abdussamadbello/echonext/graphql/generated" "github.com/abdussamadbello/echonext/graphql/model" "github.com/abdussamadbello/echonext/graphql/resolver" ) // Setup GraphQL endpoint with EchoNext func setupGraphQL() { app := echonext.New() // Create your gqlgen schema (see gqlgen docs for schema generation) schema := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{ Resolvers: &resolver.Resolver{}, })) // Configure GraphQL config := graphql.DefaultConfig(schema) config.Path = "/graphql" config.PlaygroundPath = "/playground" config.EnableIntrospection = true config.EnableTracing = true config.ComplexityLimit = 1000 // Register GraphQL endpoint app.GraphQL(config, graphql.Route{ Summary: "GraphQL API", Description: "GraphQL endpoint for queries and mutations", Tags: []string{"GraphQL"}, }) app.Start(":8080") } // Access Echo context in GraphQL resolvers type Resolver struct{} func (r *queryResolver) GetUser(ctx context.Context, id string) (*model.User, error) { // Get Echo context from GraphQL context c := graphql.GetEchoContext(ctx) if c == nil { return nil, errors.New("echo context not found") } // Access Echo context features userID := c.Get("user_id") authToken := c.Request().Header.Get("Authorization") // Get user from context helper user := graphql.GetUserFromContext(ctx, "user") // Your resolver logic here return &model.User{ ID: id, Name: "John Doe", }, nil } // WebSocket subscriptions for GraphQL func (r *subscriptionResolver) MessageAdded(ctx context.Context, roomID string) (<-chan *model.Message, error) { messages := make(chan *model.Message, 1) // Setup subscription logic go func() { // Send messages to channel messages <- &model.Message{ ID: "1", Content: "New message", RoomID: roomID, } }() return messages, nil } ``` -------------------------------- ### Configure Air for Hot Reload Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Sets up a basic Air configuration file (`.air.toml`) to enable hot reloading for your Go project. This configuration specifies the build command, the binary output, and file inclusion/exclusion rules. ```toml root = "." tmp_dir = "tmp" [build] cmd = "go build -o ./tmp/main ./cmd/api" bin = "tmp/main" include_ext = ["go"] exclude_dir = ["tmp", "vendor"] ``` -------------------------------- ### EchoNext Contrib Package Imports Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Demonstrates how to import various optional contribution packages from EchoNext, such as database helpers, configuration management, testing utilities, and middleware. These imports are used within your Go application code. ```go import ( "github.com/abdussamadbello/echonext/pkg/contrib/database" "github.com/abdussamadbello/echonext/pkg/contrib/config" "github.com/abdussamadbello/echonext/pkg/contrib/testing" "github.com/abdussamadbello/echonext/pkg/contrib/middleware" ) ``` -------------------------------- ### EchoNext Project Initialization Example Source: https://github.com/abdussamadbello/echonext/blob/master/docs/cli/overview.md Example of initializing a new EchoNext project named 'myapp' with a specific Go module path. This command sets up the basic project structure required for an EchoNext application. ```bash # Initialize project echonext init myapp --module=github.com/username/myapp # Navigate to project cd myapp # Generate a domain echonext generate domain user # Initialize database echonext db init # Run the app go mod tidy go run ./cmd/api ``` -------------------------------- ### Build Blog API with EchoNext CLI (Intermediate) Source: https://github.com/abdussamadbello/echonext/blob/master/examples/README.md Steps to build a medium complexity Blog API using EchoNext CLI. This example includes multiple domains (posts, comments, users), relationships, authentication, and file uploads. It requires the EchoNext CLI and Go. ```bash # Initialize project echonext init blog-api --module=github.com/yourusername/blog-api cd blog-api # Generate domains echonext generate domain post echonext generate domain comment echonext generate domain user echonext generate domain category # Add custom middleware echonext generate middleware auth echonext generate middleware ratelimit # Initialize database echonext db init # Run the API go mod tidy go run ./cmd/api ``` -------------------------------- ### Cross-Field Validation with Go Source: https://github.com/abdussamadbello/echonext/blob/master/docs/guides/validation.md Illustrates how to perform validation checks between different fields in a struct. Examples include confirming passwords match, and ensuring end dates are after start dates, and max prices are greater than or equal to min prices. ```go type Request struct { Password string `validate:"required,min=8" ConfirmPassword string `validate:"required,eqfield=Password" StartDate time.Time `validate:"required" EndDate time.Time `validate:"required,gtfield=StartDate" MinPrice float64 `validate:"required" MaxPrice float64 `validate:"required,gtefield=MinPrice" } ``` -------------------------------- ### EchoNext Basic Example with Middleware and Route Groups Source: https://github.com/abdussamadbello/echonext/blob/master/README.md Demonstrates initializing EchoNext, applying standard Echo middleware (Logger, CORS), creating API route groups, serving static files, and defining typed EchoNext routes within groups. It also shows how to mix typed and standard Echo handlers for file uploads. ```go app := echonext.New() // Use Echo middleware app.Use(middleware.Logger()) app.Use(middleware.CORS()) // Create route groups (standard Echo) api := app.Group("/api/v1") // Static files (standard Echo) app.Static("/assets", "public") // EchoNext typed routes work within groups api.POST("/users", createUser, echonext.Route{ Summary: "Create user", Tags: []string{"Users"}, }) // Mix typed and standard Echo handlers app.POST("/upload", func(c echo.Context) error { file, err := c.FormFile("upload") if err != nil { return err } // Standard Echo file handling return c.String(200, "Uploaded: " + file.Filename) }) ``` -------------------------------- ### Update EchoNext and Tidy Dependencies Source: https://github.com/abdussamadbello/echonext/blob/master/docs/getting-started/installation.md Updates the EchoNext package to the latest version and then tidies the go.mod file to ensure all dependencies are correctly listed and unused ones are removed. This is useful for resolving version conflicts or updating to newer versions. ```bash go get -u github.com/abdussamadbello/echonext go mod tidy ``` -------------------------------- ### Docker Deployment for Todo API Source: https://github.com/abdussamadbello/echonext/blob/master/examples/todo-api/README.md Instructions for building and running the Todo API using Docker, including the Dockerfile for building the image and docker-compose for orchestration. ```bash # Build docker build -t todo-api -f infrastructure/Dockerfile.api . # Run docker-compose up ``` -------------------------------- ### Adding Examples to OpenAPI Docs with EchoNext (Go) Source: https://github.com/abdussamadbello/echonext/blob/master/docs/faq.md Explains how to use the `example` tag in struct fields to provide example values for API documentation generated by EchoNext. This enhances the clarity of API specifications. ```go type User struct { Name string `json:"name" example:"John Doe" Age int `json:"age" example:"30" } ``` -------------------------------- ### Install EchoNext Testing Package Source: https://github.com/abdussamadbello/echonext/blob/master/docs/contrib/testing.md This command installs the EchoNext testing utilities package using go get. Ensure you have Go installed and configured correctly. ```bash go get github.com/abdussamadbello/echonext/pkg/contrib/testing ``` -------------------------------- ### Using EchoNext Database Contrib Package Source: https://github.com/abdussamadbello/echonext/blob/master/examples/todo-api/README.md Example of how to use the `database` contrib package from EchoNext to establish a database connection, using PostgreSQL as an example. ```go import "github.com/abdussamadbello/echonext/pkg/contrib/database" cfg := database.DefaultConfig() db, err := database.Connect(postgres.Open(dsn), cfg) ``` -------------------------------- ### Repository Pattern in Go Source: https://github.com/abdussamadbello/echonext/blob/master/docs/examples/README.md Shows how to implement the repository pattern in Go using Echonext's database contribution. It includes examples of initializing a generic repository and performing CRUD operations, as well as custom queries using 'Where'. Dependencies include the 'echonext/pkg/contrib/database' package. ```go import "github.com/abdussamadbello/echonext/pkg/contrib/database" repo := database.NewRepository[User](db) // CRUD operations user, err := repo.Find(1) users, err := repo.FindAll() err = repo.Create(&user) err = repo.Update(&user) err = repo.Delete(1) // Queries users, err := repo.Where("active = ?", true).FindAll() user, err := repo.Where("email = ?", email).First() ```