echox Documentation and Cookbook

repository·master·Indexed 19 days ago

https://github.com/labstack/echox

The official source repository for the Echo documentation site and its associated runnable Go cookbook recipes. It includes the Astro-based documentation site, internal design specifications, and a collection of standalone Go example applications covering topics such as automatic TLS with autocert, Casbin authorization, dynamic CORS validation, RESTful CRUD operations, and CSRF protection.

Tokens
74.4K
Snippets
248
Records
281
Agent score
64%

What's inside echox

  1. Overview of Echo features

    master

    Echo is a high-performance, minimalist Go web framework with the following core capabilities:

    • Optimized Router: Uses a Radix-tree router with zero dynamic allocation per request and smart route prioritization.
    • Batteries-included Middleware: Includes over 25 built-in middlewares such as CORS, JWT, rate-limit, gzip, recover, and request logging.
    • Data Binding: Supports binding JSON, XML, form, query, and path parameters into typed Go structs with validation.
    • Automatic TLS: Provides HTTPS out of the box via Let's Encrypt and supports HTTP/2.
    • Extensibility: Features a clean, minimal interface for composable middleware.
    • Templates: Allows plugging in any Go template engine for HTML rendering.
  2. Understand the echox repository layout

    master

    The echox repository contains the source for the Echo documentation site and its associated runnable examples. The structure is divided into three main areas:

    • site/: The documentation website built with Astro and Starlight. Documentation content is located in site/src/content/docs/.
    • cookbook/: A collection of standalone, runnable Go example applications that are referenced throughout the Echo documentation.
    • docs/: Internal design specifications.
  3. Rewrite proxy URLs using Rewrite and RegexRewrite

    master

    You can transform the request path before it reaches the upstream server using two methods:

    1. Simple Rewriting (Rewrite): Uses a map of string patterns. Asterisks (*) act as wildcards that can be referenced as $1, $2, etc.
    2. Regex Rewriting (RegexRewrite): Uses regexp.Regexp objects for complex pattern matching. Capture groups () can be referenced via $1, $2, etc.

    Both methods can be used simultaneously.

    e.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{
    	Balancer: rrb,
    	Rewrite: map[string]string{
    		"^/v1/*": "/v2/$1",
    	},
    	RegexRewrite: map[*regexp.Regexp]string{
    		regexp.MustCompile("^/foo/([0-9].*)"):  "/num/$1",
    		regexp.MustCompile("^/bar/(.+?)/(.*)"): "/baz/$2/$1",
    	},
    }))
  4. Implement custom Echo middleware

    master

    In Echo, a middleware is a function with the signature func(next echo.HandlerFunc) echo.HandlerFunc.

    To implement middleware, you wrap the next handler. You can perform actions before calling next(c) (to intercept the request) or after calling next(c) (to intercept the response).

    When intercepting the response, you can use echo.UnwrapResponse(c.Response()) to access the underlying response writer and retrieve the HTTP status code.

    func MyMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
    	return func(c *echo.Context) error {
    		// Logic before the handler
    		err := next(c)
    		// Logic after the handler
    		return err
    	}
    }
  5. Understand binding precedence for multiple sources

    master

    A single struct field can declare multiple sources via tags. When multiple sources are present, data is bound in the following order, with each subsequent step overwriting the previous value:

    1. Path parameters
    2. Query parameters (typically for GET/DELETE)
    3. Request body
    type User struct {
    	ID string `param:"id" query:"id" form:"id" json:"id" xml:"id"`
    }
  6. Access the CSRF token

    master

    Once the middleware is active, you can access the token in two ways:

    1. Server-side: The token is stored in the echo.Context under the key specified by ContextKey (defaults to "csrf"). You can retrieve this to pass it to your HTML templates.
    2. Client-side: The token can be read directly from the CSRF cookie (default name is _csrf).
  7. Understand the echo.Context abstraction

    master

    The echo.Context (passed as *echo.Context to handlers and middleware) is the central object representing the current HTTP request. It encapsulates the request and response, path parameters, bound data, and provides helper methods for reading input and writing responses.

    func handler(c *echo.Context) error {
    	// c carries request/response data and helpers
    	return nil
    }
  8. Prevent path doubling in groups using IgnoreBase

    master

    When applying Static middleware to a non-root group, the middleware defaults to appending the URL path to the filesystem path. This can result in 'doubled' paths. To prevent this and ensure the filesystem path is not doubled, set IgnoreBase: true in your StaticConfig.

    // Default behavior (path doubling):
    // If group is /somepath and middleware root is 'filesystempath'
    // A request for /somepath/file.txt looks for 'filesystempath/somepath/file.txt'
    
    // To fix (using IgnoreBase):
    // group.Use(middleware.StaticWithConfig(middleware.StaticConfig{
    //     Root: "filesystempath",
    //     IgnoreBase: true,
    // }))
  9. Validate origins dynamically with UnsafeAllowOriginFunc

    master

    If you need to allow origins based on dynamic logic (e.g., allowing any subdomain of a specific domain), use the UnsafeAllowOriginFunc field in CORSConfig. When this function is provided, the AllowOrigins field is ignored.

    Security Warning: Use extreme caution. Attackers may register hostile (sub)domain names that match your validation logic.

    // Sub-domain check example:
    UnsafeAllowOriginFunc: func(c *echo.Context, origin string) (string, bool, error) {
    	if strings.HasSuffix(origin, ".example.com") {
    		return origin, true, nil
    	}
    	return "", false, nil
    }