Skip to main content

Echo CLI Tools

Introduction

Command-line interface (CLI) tools are essential components in a developer's toolkit, enabling faster development, automation of repetitive tasks, and consistent project structures. Echo, the high-performance Go web framework, offers CLI tooling to streamline your development workflow.

In this guide, we'll explore Echo's CLI tools that help you generate, manage, and deploy Echo applications more efficiently. These tools are particularly valuable for beginners as they provide a structured approach to building Echo applications and reduce the initial learning curve.

Getting Started with Echo CLI

Installation

Before using Echo's CLI tools, you need to install them. The primary CLI tool for Echo is called echogen, which you can install using Go's package manager:

bash
go install github.com/labstack/echo/v4/cmd/echogen@latest

After installation, verify that the tool is correctly installed by running:

bash
echogen --version

Expected output:

echogen version x.x.x

Core Echo CLI Tools

echogen - Project Generator

The echogen tool helps you scaffold a new Echo application with a standardized structure. This saves time and ensures you follow best practices from the start.

Creating a New Project

bash
echogen new my-echo-app

This command generates a new Echo project with the following structure:

my-echo-app/
├── cmd/
│ └── server/
│ └── main.go
├── internal/
│ ├── handler/
│ ├── middleware/
│ └── model/
├── static/
├── templates/
├── go.mod
└── go.sum

Generated Main File

The generated main.go typically looks like this:

go
package main

import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

func main() {
// Echo instance
e := echo.New()

// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Routes
e.GET("/", hello)

// Start server
e.Logger.Fatal(e.Start(":8080"))
}

// Handler
func hello(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}

Generating Handlers

The echogen tool can also help you generate handler files with proper structure:

bash
echogen handler user

This creates a new file in the internal/handler directory with basic CRUD operations for a "user" resource:

go
// internal/handler/user.go
package handler

import (
"net/http"

"github.com/labstack/echo/v4"
)

// UserHandler handles user-related requests
type UserHandler struct {
// Add dependencies here (e.g., services, repositories)
}

// NewUserHandler creates a new UserHandler
func NewUserHandler() *UserHandler {
return &UserHandler{}
}

// GetAll returns all users
func (h *UserHandler) GetAll(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{"message": "Get all users"})
}

// GetByID returns a user by ID
func (h *UserHandler) GetByID(c echo.Context) error {
id := c.Param("id")
return c.JSON(http.StatusOK, map[string]string{"message": "Get user by ID", "id": id})
}

// Create creates a new user
func (h *UserHandler) Create(c echo.Context) error {
return c.JSON(http.StatusCreated, map[string]string{"message": "Create user"})
}

// Update updates a user
func (h *UserHandler) Update(c echo.Context) error {
id := c.Param("id")
return c.JSON(http.StatusOK, map[string]string{"message": "Update user", "id": id})
}

// Delete deletes a user
func (h *UserHandler) Delete(c echo.Context) error {
id := c.Param("id")
return c.JSON(http.StatusNoContent, nil)
}

Additional CLI Tools

echotest - Test Generator

Although not part of the core Echo CLI tools, there's a community package called echotest that generates tests for your Echo application:

bash
go install github.com/labstack/echotest@latest

Once installed, you can generate tests for your handlers:

bash
echotest generate -f internal/handler/user.go

This creates a test file with pre-populated test cases for each handler method:

go
// internal/handler/user_test.go
package handler_test

import (
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"

"your-module/internal/handler"
)

func TestUserHandler_GetAll(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/users", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

// Handler
h := handler.NewUserHandler()

// Assertions
if assert.NoError(t, h.GetAll(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
}
}

// Additional test functions for other methods...

Real-World Usage Examples

Example 1: Creating a REST API

Let's walk through creating a simple REST API using Echo CLI tools:

bash
# Generate a new project
echogen new todo-api

# Change to the project directory
cd todo-api

# Generate a task handler
echogen handler task

# Generate a user handler
echogen handler user

Now, update your main.go to register these handlers:

go
package main

import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"

"todo-api/internal/handler"
)

func main() {
e := echo.New()

// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Handlers
taskHandler := handler.NewTaskHandler()
userHandler := handler.NewUserHandler()

// Routes
e.GET("/tasks", taskHandler.GetAll)
e.POST("/tasks", taskHandler.Create)
e.GET("/tasks/:id", taskHandler.GetByID)
e.PUT("/tasks/:id", taskHandler.Update)
e.DELETE("/tasks/:id", taskHandler.Delete)

e.GET("/users", userHandler.GetAll)
e.POST("/users", userHandler.Create)
e.GET("/users/:id", userHandler.GetByID)
e.PUT("/users/:id", userHandler.Update)
e.DELETE("/users/:id", userHandler.Delete)

// Start server
e.Logger.Fatal(e.Start(":8080"))
}

Example 2: Creating a Web Application with Templates

For a web application using Echo's template rendering:

bash
# Generate a new project
echogen new web-app

# Change to the project directory
cd web-app

# Create template directories
mkdir -p templates/layouts templates/pages

# Create a base layout
echo '<html><head><title>{{ .title }}</title></head><body>{{ .content }}</body></html>' > templates/layouts/base.html

# Create a home page
echo '<h1>Welcome to Our Web App</h1><p>{{ .message }}</p>' > templates/pages/home.html

Update your main.go to use templates:

go
package main

import (
"html/template"
"io"
"net/http"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

// TemplateRenderer is a custom HTML template renderer
type TemplateRenderer struct {
templates *template.Template
}

// Render renders a template document
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
e := echo.New()

// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())

// Template renderer
renderer := &TemplateRenderer{
templates: template.Must(template.ParseGlob("templates/**/*.html")),
}
e.Renderer = renderer

// Routes
e.GET("/", func(c echo.Context) error {
return c.Render(http.StatusOK, "home.html", map[string]interface{}{
"title": "Home Page",
"message": "Welcome to our Echo web application!",
})
})

// Static files
e.Static("/static", "static")

// Start server
e.Logger.Fatal(e.Start(":8080"))
}

Best Practices and Tips

  1. Project Structure: Always maintain the generated project structure for consistency.

  2. Version Control: Initialize a Git repository immediately after generating a new project:

    bash
    git init
  3. Dependency Management: Regularly update your dependencies:

    bash
    go get -u all
  4. Environment Configuration: Use environment variables for configuration instead of hardcoding values:

    go
    port := os.Getenv("PORT")
    if port == "" {
    port = "8080"
    }
    e.Start(":" + port)
  5. Testing: Generate and maintain tests for all handlers to ensure reliability.

Summary

Echo's CLI tools significantly speed up development by automating repetitive tasks and enforcing consistent project structures. The echogen tool is particularly useful for beginners as it provides scaffolding with best practices built-in.

By using these tools, you can:

  • Quickly bootstrap new Echo applications
  • Generate handler boilerplate code
  • Maintain a consistent, organized project structure
  • Focus on your business logic rather than setup details

As you become more familiar with Echo, you may find additional ways to extend and customize these tools for your specific needs.

Additional Resources

  1. Official Echo Documentation
  2. Echo GitHub Repository
  3. Community-contributed Echo Tools

Exercises

  1. Basic Project: Use echogen to create a new Echo project and implement a simple "Hello, World!" endpoint.

  2. REST API: Create a complete REST API for a "book store" with endpoints for books, authors, and categories.

  3. Advanced UI: Build a web application with Echo that uses templates to render pages and implements form handling for user registration and login.

  4. Custom CLI Tool: Try extending echogen with your own custom generator for a specific use case in your project.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)