Echo Web Framework

repository·master·Indexed 12 days ago

https://github.com/labstack/echo

A high-performance, extensible, and minimalist Go web framework built on top of the standard net/http library. Echo v5 features a fast radix-tree router, request binding, a deep middleware ecosystem, and support for structured logging via log/slog. It provides type-safe generic parameter extraction, virtual host support, and a flexible Router interface for building scalable RESTful APIs.

Tokens
21.7K
Snippets
88
Records
111
Agent score
98%

What's inside Echo

  1. Configure and use the new Router interface

    master

    Echo v5 introduces a Router interface to allow for different routing implementations. The default implementation is DefaultRouter.

    • Use NewRouter(config RouterConfig) to create a new router (it no longer takes *Echo).
    • Echo.Router() now returns the Router interface instead of a concrete *Router.
    • NewConcurrentRouter(r Router) Router is available for thread-safe routing.
  2. Manage path parameters with PathValues

    master

    Echo v5 replaces the old ParamNames() and ParamValues() methods with a structured PathValues type. This type allows for more efficient handling of path parameters.

    PathValue Structure:

    • Name: The parameter name.
    • Value: The parameter value.

    Methods:

    • PathValues.Get(name string) (string, bool): Retrieves a value by name.
    • PathValues.GetOr(name string, defaultValue string) string: Retrieves a value or returns a default.

    Context Integration:

    • (c *Context) PathValues() PathValues: Returns the current path values.
    • (c *Context) SetPathValues(pathValues PathValues): Sets the path values.
    type PathValue struct {
        Name  string
        Value string
    }
    
    type PathValues []PathValue
    
    func (p PathValues) Get(name string) (string, bool)
    func (p PathValues) GetOr(name string, defaultValue string) string
    
    func (c *Context) PathValues() PathValues
    func (c *Context) SetPathValues(pathValues PathValues)
  3. Interoperate with net/http

    master

    Echo is built on Go's standard net/http library. You can interoperate with standard library handlers and middleware using:

    • echo.WrapHandler for standard handlers.
    • echo.WrapMiddleware for standard middleware.
  4. Understand Echo version support and policies

    master

    Echo maintains two active release lines with different support levels:

    • v5 (Current): The primary development line receiving new features, fixes, and improvements. It has been the current line since 2026-01-18.
    • v4 (Maintenance / LTS): Receives only security and bug fixes. Support for this line ends on 2026-12-31.

    Echo is designed to support the latest four Go major releases, though compatibility with older versions may be possible.

  5. Configure Server Startup in v5

    master

    Echo v5 has simplified the Start methods. For advanced configurations like graceful shutdown or custom TLS, use the echo.StartConfig type.

    Simple Startup:

    e.Start(":8080")

    Advanced Startup with Graceful Shutdown:

    ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
    defer cancel()
    sc := echo.StartConfig{Address: ":8080"}
    sc.Start(ctx, e)
  6. Best practices for developing Echo middleware

    master

    When creating custom middleware for the Echo framework, follow these guidelines to ensure compatibility and robust error handling:

    • Avoid Panics in Creators: Do not use panic inside middleware creator functions when handling invalid configurations. Instead, prefer returning errors if the configuration is invalid.
    • Error Handling in Request Flow: When an error occurs during request handling within a middleware, do not simply call c.Error() and return nil. Instead, return the error from the middleware function. This allows preceding middlewares in the call chain to implement specific logic for handling returned errors.
    • Use Configuration Structs: Implement the MiddlewareConfigurator interface for your middleware configuration structs. This allows you to explicitly decide whether the middleware should panic or return errors when encountering configuration issues.
    • Standardize Context Placement: When including echo.Context in function signatures or struct fields, always make it the first parameter. This ensures consistency across all functions that utilize the Echo context.
  7. Quick start with Echo

    master

    To create a basic Echo server, initialize a new Echo instance using echo.New(), define your routes, and start the server with e.Start(address). You can also use middleware like middleware.RequestLogger() and middleware.Recover() to enhance functionality.

    Handlers receive an *echo.Context and should return an error.

    package main
    
    import (
      "github.com/labstack/echo/v5"
      "github.com/labstack/echo/v5/middleware"
      "log/slog"
      "net/http"
    )
    
    func main() {
      // Echo instance
      e := echo.New()
    
      // Middleware
      e.Use(middleware.RequestLogger()) // use the RequestLogger middleware with slog logger
      e.Use(middleware.Recover())       // recover panics as errors for proper error handling
    
      // Routes
      e.GET("/", hello)
    
      // Start server
      if err := e.Start(":8080"); err != nil {
        slog.Error("failed to start server", "error", err)
      }
    }
    
    // Handler
    func hello(c *echo.Context) error {
      return c.String(http.StatusOK, "Hello, World!")
    }
  8. Generate a self-signed certificate and private key with OpenSSL

    master

    To generate a valid certificate (cert.pem) and private key (key.pem) for local development (e.g., for HTTPS/TLS in Echo), use the following command. This command is compatible with OpenSSL version 1.1.1 or higher and includes necessary Subject Alternative Names (SAN) for localhost and loopback IP addresses.

    # In OpenSSL ≥ 1.1.1
    openssl req -x509 -newkey rsa:4096 -sha256 -days 9999 -nodes \
      -keyout key.pem -out cert.pem -subj "/CN=localhost" \
      -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1"
  9. Update Handler Signatures for v5

    master

    In Echo v5, the Context is passed as a pointer. All handler functions must be updated to reflect this change.

    v4 Signature: func MyHandler(c echo.Context) error

    v5 Signature: func MyHandler(c *echo.Context) error

    // v5
    func MyHandler(c *echo.Context) error { ... }
  10. Migrate Echo handlers to use *echo.Context

    master

    In Echo v5, Context has changed from an interface to a concrete struct. This is a critical breaking change: all handler functions must now accept a pointer to the context (*echo.Context) instead of the interface (echo.Context).

    // Before (v4)
    func MyHandler(c echo.Context) error {
        return c.JSON(200, map[string]string{"hello": "world"})
    }
    
    // After (v5)
    func MyHandler(c *echo.Context) error {
        return c.JSON(200, map[string]string{"hello": "world"})
    }
  11. Migrate from Echo v4 to v5

    master

    To migrate an existing project from Echo v4 to v5, follow these primary steps:

    1. Update Imports: Change all echo/v4 imports to echo/v5.
    2. Update Context Type: Change all occurrences of echo.Context to *echo.Context (it is now a pointer).
    3. Update Handler Signatures: Ensure all handlers accept *echo.Context.
    4. Update Error Handlers: The HTTPErrorHandler signature has swapped parameters from (err, c) to (c, err).
    5. Update Server Startup: Use echo.StartConfig for advanced configurations instead of specialized Start methods.
    6. Update Router Access: Access routes via e.Router().Routes() instead of e.Routes().

    On Linux, you can automate the import and context pointer updates using sed:

    find . -type f -name "*.go" -exec sed -i 's/ echo.Context/ *echo.Context/g' {} +
    find . -type f -name "echo\/v4" -exec sed -i 's/echo\/v5/g' {} +
  12. Use slog.Logger for logging in Echo v5

    master

    Echo v5 has removed the custom Logger interface in favor of Go's standard library structured logging (log/slog).

    • The Echo.Logger field is now a *slog.Logger.
    • Context.Logger() now returns a *slog.Logger.
    • Use Context.SetLogger(logger *slog.Logger) to set a logger on the context.