echo

package
v1.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

Echo HTTP Server Package

Echo web framework wrapper package for Go.

Features

  • Based on Echo v4: High-performance web framework
  • Easy routing: GET, POST, PUT, DELETE, PATCH methods
  • Group routing: URL path grouping support
  • Middleware: Global and route-specific middleware
  • Graceful Shutdown: Timeout-based safe shutdown
  • Thread-safe: Concurrency safety guaranteed

Installation

go get github.com/common-library/go/http/echo
go get github.com/labstack/echo/v4

When to Choose Echo

  • ✅ API servers where high performance is critical
  • ✅ When middleware chains are needed
  • ✅ Data binding and validation features required
  • ✅ WebSocket support needed
  • ✅ Preference for concise APIs

Usage Examples

Basic Server
package main

import (
    "net/http"
    "github.com/common-library/go/http/echo"
    echo_lib "github.com/labstack/echo/v4"
)

func main() {
    server := &echo.Server{}
    
    // Simple handler
    server.RegisterHandler(echo_lib.GET, "/", func(c echo_lib.Context) error {
        return c.String(http.StatusOK, "Hello, World!")
    })
    
    // JSON response
    server.RegisterHandler(echo_lib.GET, "/api/hello", func(c echo_lib.Context) error {
        return c.JSON(http.StatusOK, map[string]string{
            "message": "Hello from Echo",
        })
    })
    
    // Start server
    err := server.Start(":8080", func(err error) {
        log.Fatalf("Server error: %v", err)
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Wait for shutdown
    select {}
}
Route Registration Methods
server := &echo.Server{}

// Basic registration
server.RegisterHandler(echo_lib.GET, "/users", getUsersHandler)
server.RegisterHandler(echo_lib.POST, "/users", createUserHandler)
server.RegisterHandler(echo_lib.PUT, "/users/:id", updateUserHandler)
server.RegisterHandler(echo_lib.DELETE, "/users/:id", deleteUserHandler)
server.RegisterHandler(echo_lib.PATCH, "/users/:id", patchUserHandler)

// Register handler for all HTTP methods (GET, POST, PUT, DELETE, etc.)
server.RegisterHandlerAny("/webhook", webhookHandler)

// Register with middleware
server.RegisterHandler(echo_lib.GET, "/admin", adminHandler, authMiddleware, logMiddleware)
server.RegisterHandlerAny("/api/catch-all", catchAllHandler, authMiddleware)
Wrapping Standard HTTP Handlers
import (
    "net/http"
    "github.com/common-library/go/http/echo"
)

// Wrap http.Handler (e.g., http.FileServer)
fs := http.FileServer(http.Dir("./static"))
server.RegisterHandler(echo_lib.GET, "/static/*", echo.WrapHandler(fs))

// Wrap http.HandlerFunc - Method 1: Using WrapHandler
stdHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello from standard handler"))
})
server.RegisterHandler(echo_lib.GET, "/std1", echo.WrapHandler(stdHandler))

// Wrap http.HandlerFunc - Method 2: Using WrapHandlerFunc (recommended)
handler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}
server.RegisterHandler(echo_lib.GET, "/std2", echo.WrapHandlerFunc(handler))

// Wrap third-party handlers
server.RegisterHandler(echo_lib.GET, "/prometheus", echo.WrapHandler(promhttp.Handler()))
Group Routing
server := &echo.Server{}

// Create API group
api := server.Group("/api")

// Routes within group
api.GET("/users", func(c echo_lib.Context) error {
    return c.JSON(http.StatusOK, users)
}
})

api.POST("/users", func(c echo_lib.Context) error {
    // Create user logic
    return c.JSON(http.StatusCreated, newUser)
})

// Nested groups
v1 := api.Group("/v1")
v1.GET("/info", func(c echo_lib.Context) error {
    return c.JSON(http.StatusOK, map[string]string{"version": "1.0"})
})

// Group-specific middleware
admin := api.Group("/admin", adminAuthMiddleware)
admin.GET("/stats", getStatsHandler)
Middleware Usage
import "github.com/labstack/echo/v4/middleware"

server := &echo.Server{}

// Global middleware
server.Use(middleware.Logger())
server.Use(middleware.Recover())
server.Use(middleware.CORS())

// Route-specific middleware
authMiddleware := func(next echo_lib.HandlerFunc) echo_lib.HandlerFunc {
    return func(c echo_lib.Context) error {
        token := c.Request().Header.Get("Authorization")
        if token == "" {
            return echo_lib.NewHTTPError(http.StatusUnauthorized, "missing token")
        }
        return next(c)
    }
}

server.RegisterHandler(echo_lib.GET, "/protected", protectedHandler, authMiddleware)
Request Processing Examples
// Path parameters
server.RegisterHandler(echo_lib.GET, "/users/:id", func(c echo_lib.Context) error {
    id := c.Param("id")
    return c.String(http.StatusOK, "User ID: "+id)
})

// Query parameters
server.RegisterHandler(echo_lib.GET, "/search", func(c echo_lib.Context) error {
    query := c.QueryParam("q")
    page := c.QueryParam("page")
    return c.JSON(http.StatusOK, map[string]string{
        "query": query,
        "page":  page,
    })
})

// JSON binding
type User struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
}

server.RegisterHandler(echo_lib.POST, "/users", func(c echo_lib.Context) error {
    u := new(User)
    if err := c.Bind(u); err != nil {
        return err
    }
    if err := c.Validate(u); err != nil {
        return err
    }
    return c.JSON(http.StatusCreated, u)
})
Graceful Shutdown
import (
    "os"
    "os/signal"
    "syscall"
    "time"
)

server := &echo.Server{}
server.RegisterHandler(echo_lib.GET, "/", homeHandler)

// Start server
server.Start(":8080", func(err error) {
    log.Printf("Server error: %v", err)
})

// Wait for signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit

// Graceful shutdown (10 second timeout)
log.Println("Shutting down server...")
if err := server.Stop(10 * time.Second); err != nil {
    log.Fatal(err)
}
log.Println("Server stopped")
Direct Echo Instance Access
server := &echo.Server{}

// Get Echo instance
e := server.GetEcho()

// Advanced settings
e.HideBanner = true
e.Debug = false
e.Server.ReadTimeout = 30 * time.Second
e.Server.WriteTimeout = 30 * time.Second

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

// File upload
e.POST("/upload", uploadHandler)

API Documentation

Server
RegisterHandler(method, path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc)

Registers an HTTP handler for a specific method.

  • method: HTTP method (echo.GET, echo.POST, etc.)
  • path: URL path pattern
  • handler: Echo handler function
  • middleware: Optional middleware
RegisterHandlerAny(path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc)

Registers an HTTP handler for all HTTP methods (GET, POST, PUT, DELETE, PATCH, etc.).

  • path: URL path pattern
  • handler: Echo handler function
  • middleware: Optional middleware
WrapHandler(handler http.Handler) echo.HandlerFunc

Wraps a standard http.Handler into an Echo handler function.

  • handler: Standard http.Handler to wrap
  • return: Echo-compatible handler function

Use this for wrapping http.FileServer, third-party handlers, or any type implementing http.Handler.

WrapHandlerFunc(handlerFunc http.HandlerFunc) echo.HandlerFunc

Wraps a standard http.HandlerFunc into an Echo handler function.

  • handlerFunc: Standard http.HandlerFunc to wrap
  • return: Echo-compatible handler function

This is a convenience function for wrapping function types directly without type conversion.

Use(middleware ...echo.MiddlewareFunc)

Registers global middleware.

Group(prefix string, middleware ...echo.MiddlewareFunc) *echo.Group

Creates a router group.

  • prefix: Group path prefix
  • middleware: Group middleware
  • return: Echo Group instance
Start(address string, listenAndServeFailureFunc func(err error)) error

Starts the server.

  • address: Server address (e.g., ":8080")
  • listenAndServeFailureFunc: Error callback (excludes http.ErrServerClosed)
Stop(shutdownTimeout time.Duration) error

Safely shuts down the server.

  • shutdownTimeout: Shutdown wait time
IsRunning() bool

Returns the server running status.

GetEcho() *echo.Echo

Provides direct access to the Echo instance.

Framework Comparison

Feature Echo Gin Gorilla Mux
Performance ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐
Learning Curve Easy Easy Medium
Middleware Rich Rich Basic
Data Binding
Validation
WebSocket
Community Active Very Active Active

Notes

  • Echo handlers must return error
  • Middleware order matters (Logger → Recover sequence recommended)
  • http.ErrServerClosed is considered normal shutdown and won't trigger the error callback
  • Cannot start multiple servers on the same port

References

License

This package follows the project's license.

Documentation

Overview

Package echo provides a simplified wrapper around the Echo web framework.

This package offers convenient methods for creating and managing Echo HTTP servers with support for routing, middleware, and graceful shutdown.

Features:

  • Simplified server setup with Echo v4
  • Handler and middleware registration
  • Group routing support
  • Graceful shutdown with timeout
  • Thread-safe operations

Example:

server := &echo.Server{}
server.RegisterHandler(echo.GET, "/hello", func(c echo.Context) error {
    return c.String(200, "Hello, World!")
})
server.Start(":8080", nil)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WrapHandler

func WrapHandler(handler http.Handler) echo.HandlerFunc

WrapHandler wraps a standard http.Handler into an Echo handler function.

This function allows you to use standard Go http.Handler implementations (such as http.FileServer, third-party handlers, or http.HandlerFunc) within the Echo framework.

Parameters:

  • handler: Standard http.Handler to wrap

Returns:

  • echo.HandlerFunc: Echo-compatible handler function

Example:

// Wrap http.FileServer
fs := http.FileServer(http.Dir("./static"))
server.RegisterHandler(echo.GET, "/static/*", WrapHandler(fs))

// Wrap http.HandlerFunc
stdHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello from standard handler"))
})
server.RegisterHandler(echo.GET, "/std", WrapHandler(stdHandler))

func WrapHandlerFunc

func WrapHandlerFunc(handlerFunc http.HandlerFunc) echo.HandlerFunc

WrapHandlerFunc wraps a standard http.HandlerFunc into an Echo handler function.

This is a convenience function that wraps http.HandlerFunc (a function type) into an Echo-compatible handler. It's functionally equivalent to WrapHandler but provides better type clarity when working with HandlerFunc types.

Parameters:

  • handlerFunc: Standard http.HandlerFunc to wrap

Returns:

  • echo.HandlerFunc: Echo-compatible handler function

Example:

// Wrap a HandlerFunc directly
handler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}
server.RegisterHandler(echo.GET, "/hello", WrapHandlerFunc(handler))

// Or use with http.HandlerFunc type conversion
server.RegisterHandler(echo.POST, "/api", WrapHandlerFunc(
    http.HandlerFunc(myStandardHandler),
))

Types

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a struct that provides Echo HTTP server related methods.

func (*Server) GetEcho

func (s *Server) GetEcho() *echo.Echo

GetEcho returns the underlying Echo instance for advanced usage.

Returns:

  • *echo.Echo: Echo instance

Use this method when you need direct access to Echo's API for advanced configuration.

Example:

e := server.GetEcho()
e.HideBanner = true
e.Debug = true

func (*Server) Group

func (s *Server) Group(prefix string, middleware ...echo.MiddlewareFunc) *echo.Group

Group creates a new router group with optional middleware.

Parameters:

  • prefix: Path prefix for the group
  • middleware: Optional middleware functions for the group

Returns:

  • *echo.Group: Echo router group

Example:

api := server.Group("/api/v1")
api.GET("/users", getUsersHandler)

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns whether the server is currently running.

Returns:

  • bool: true if server is running, false otherwise

Example:

if server.IsRunning() {
    fmt.Println("Server is active")
}

func (*Server) RegisterHandler

func (s *Server) RegisterHandler(method string, path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc)

RegisterHandler registers an HTTP handler with optional middleware.

Parameters:

  • method: HTTP method (echo.GET, echo.POST, etc.)
  • path: URL path pattern
  • handler: Echo handler function
  • middleware: Optional middleware functions

Example:

server.RegisterHandler(echo.GET, "/users/:id", getUserHandler)

func (*Server) RegisterHandlerAny

func (s *Server) RegisterHandlerAny(path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc)

RegisterHandlerAny registers an HTTP handler for all methods (GET, POST, PUT, DELETE, etc.) with optional middleware.

Parameters:

  • path: URL path pattern
  • handler: Echo handler function
  • middleware: Optional middleware functions

Example:

server.RegisterHandlerAny("/users/:id", getUserHandler)

func (*Server) Start

func (s *Server) Start(address string, listenAndServeFailureFunc func(err error)) error

Start starts the Echo HTTP server.

Parameters:

  • address: Server address (e.g., ":8080", "localhost:3000")
  • listenAndServeFailureFunc: Optional callback for server errors (excluding graceful shutdown)

Returns:

  • error: Error if server is already running or fails to start

The server runs in a background goroutine. Use Stop() for graceful shutdown.

Example:

err := server.Start(":8080", func(err error) {
    log.Printf("Server error: %v", err)
})

func (*Server) Stop

func (s *Server) Stop(shutdownTimeout time.Duration) error

Stop gracefully shuts down the Echo server.

Parameters:

  • shutdownTimeout: Maximum time to wait for shutdown

Returns:

  • error: Error if shutdown fails

Example:

err := server.Stop(10 * time.Second)

func (*Server) Use

func (s *Server) Use(middleware ...echo.MiddlewareFunc)

Use registers global middleware.

Parameters:

  • middleware: Middleware functions to apply globally

Example:

server.Use(middleware.Logger(), middleware.Recover())

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL