API Reference
github.com/labstack/echo/v5
diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml new file mode 100644 index 000000000..51d11cd43 --- /dev/null +++ b/.github/workflows/deploy-docs.yml @@ -0,0 +1,39 @@ +name: Deploy API Docs to GitHub Pages + +on: + push: + branches: [main] + paths: + - 'docs/**' + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Pages + uses: actions/configure-pages@v5 + + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: docs/api-reference + + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/docs/api-reference/_og/api-reference.png b/docs/api-reference/_og/api-reference.png new file mode 100644 index 000000000..8a460936f Binary files /dev/null and b/docs/api-reference/_og/api-reference.png differ diff --git a/docs/api-reference/_og/api-reference/package-root.png b/docs/api-reference/_og/api-reference/package-root.png new file mode 100644 index 000000000..c92b3ff67 Binary files /dev/null and b/docs/api-reference/_og/api-reference/package-root.png differ diff --git a/docs/api-reference/_og/api-reference/pkg-echotest.png b/docs/api-reference/_og/api-reference/pkg-echotest.png new file mode 100644 index 000000000..e9b5ebbc0 Binary files /dev/null and b/docs/api-reference/_og/api-reference/pkg-echotest.png differ diff --git a/docs/api-reference/_og/api-reference/pkg-middleware.png b/docs/api-reference/_og/api-reference/pkg-middleware.png new file mode 100644 index 000000000..b5c899b48 Binary files /dev/null and b/docs/api-reference/_og/api-reference/pkg-middleware.png differ diff --git a/docs/api-reference/api-reference.html b/docs/api-reference/api-reference.html new file mode 100644 index 000000000..033c44a4c --- /dev/null +++ b/docs/api-reference/api-reference.html @@ -0,0 +1,28 @@ + +
github.com/labstack/echo/v5
import "github.com/labstack/echo/v5"
Package echo implements high performance, minimalist Go web framework.
+Example:
+package main
+
+import (
+ "log/slog"
+ "net/http"
+
+ "github.com/labstack/echo/v5"
+ "github.com/labstack/echo/v5/middleware"
+)
+
+// Handler
+func hello(c *echo.Context) error {
+ return c.String(http.StatusOK, "Hello, World!")
+}
+
+func main() {
+ // Echo instance
+ e := echo.New()
+
+ // Middleware
+ e.Use(middleware.RequestLogger())
+ e.Use(middleware.Recover())
+
+ // Routes
+ e.GET("/", hello)
+
+ // Start server
+ if err := e.Start(":8080"); err != nil {
+ slog.Error("failed to start server", "error", err)
+ }
+}Learn more at https://echo.labstack.com
TimeLayout constants for parsing Unix timestamps in different precisions.
const (
+ TimeLayoutUnixTime = TimeLayout("UnixTime") // Unix timestamp in seconds
+ TimeLayoutUnixTimeMilli = TimeLayout("UnixTimeMilli") // Unix timestamp in milliseconds
+ TimeLayoutUnixTimeNano = TimeLayout("UnixTimeNano") // Unix timestamp in nanoseconds
+)MIME types
const (
+ // MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259
+ MIMEApplicationJSON = "application/json"
+ // Deprecated: Please use MIMEApplicationJSON instead. JSON should be encoded using UTF-8 by default.
+ // No "charset" parameter is defined for this registration.
+ // Adding one really has no effect on compliant recipients.
+ // See RFC 8259, section 8.1. https://datatracker.ietf.org/doc/html/rfc8259#section-8.1n"
+ MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
+ MIMEApplicationJavaScript = "application/javascript"
+ MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
+ MIMEApplicationXML = "application/xml"
+ MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8
+ MIMETextXML = "text/xml"
+ MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8
+ MIMEApplicationForm = "application/x-www-form-urlencoded"
+ MIMEApplicationProtobuf = "application/protobuf"
+ MIMEApplicationMsgpack = "application/msgpack"
+ MIMETextHTML = "text/html"
+ MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8
+ MIMETextPlain = "text/plain"
+ MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8
+ MIMEMultipartForm = "multipart/form-data"
+ MIMEOctetStream = "application/octet-stream"
+)const (
+
+ // PROPFIND Method can be used on collection and property resources.
+ PROPFIND = "PROPFIND"
+ // REPORT Method can be used to get information about a resource, see rfc 3253
+ REPORT = "REPORT"
+ // QUERY Method is a safe, idempotent request method carrying request content (a query) in its body, see rfc 10008.
+ // It is not (yet) part of the `net/http` standard library, so Echo defines it here.
+ QUERY = "QUERY"
+ // RouteNotFound is special method type for routes handling "route not found" (404) cases
+ RouteNotFound = "echo_route_not_found"
+ // RouteAny is special method type that matches any HTTP method in request. Any has lower
+ // priority that other methods that have been registered with Router to that path.
+ RouteAny = "echo_route_any"
+)Headers
const (
+ HeaderAccept = "Accept"
+ HeaderAcceptEncoding = "Accept-Encoding"
+ // HeaderAllow is the name of the "Allow" header field used to list the set of methods
+ // advertised as supported by the target resource. Returning an Allow header is mandatory
+ // for status 405 (method not found) and useful for the OPTIONS method in responses.
+ // See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1
+ HeaderAllow = "Allow"
+ HeaderAuthorization = "Authorization"
+ HeaderContentDisposition = "Content-Disposition"
+ HeaderContentEncoding = "Content-Encoding"
+ HeaderContentLength = "Content-Length"
+ HeaderContentType = "Content-Type"
+ HeaderCookie = "Cookie"
+ HeaderSetCookie = "Set-Cookie"
+ HeaderIfModifiedSince = "If-Modified-Since"
+ HeaderLastModified = "Last-Modified"
+ HeaderLocation = "Location"
+ HeaderRetryAfter = "Retry-After"
+ HeaderUpgrade = "Upgrade"
+ HeaderVary = "Vary"
+ HeaderWWWAuthenticate = "WWW-Authenticate"
+ HeaderXForwardedFor = "X-Forwarded-For"
+ HeaderXForwardedProto = "X-Forwarded-Proto"
+ HeaderXForwardedProtocol = "X-Forwarded-Protocol"
+ HeaderXForwardedSsl = "X-Forwarded-Ssl"
+ HeaderXUrlScheme = "X-Url-Scheme"
+ HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
+ HeaderXRealIP = "X-Real-Ip"
+ HeaderXRequestID = "X-Request-Id"
+ HeaderXCorrelationID = "X-Correlation-Id"
+ HeaderXRequestedWith = "X-Requested-With"
+ HeaderServer = "Server"
+
+ // HeaderOrigin request header indicates the origin (scheme, hostname, and port) that caused the request.
+ // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
+ HeaderOrigin = "Origin"
+ HeaderCacheControl = "Cache-Control"
+ HeaderConnection = "Connection"
+
+ // Access control
+ HeaderAccessControlRequestMethod = "Access-Control-Request-Method"
+ HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
+ HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"
+ HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"
+ HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"
+ HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
+ HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"
+ HeaderAccessControlMaxAge = "Access-Control-Max-Age"
+
+ // Security
+ HeaderStrictTransportSecurity = "Strict-Transport-Security"
+ HeaderXContentTypeOptions = "X-Content-Type-Options"
+ HeaderXXSSProtection = "X-XSS-Protection"
+ HeaderXFrameOptions = "X-Frame-Options"
+ HeaderContentSecurityPolicy = "Content-Security-Policy"
+ HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
+ HeaderXCSRFToken = "X-CSRF-Token" // #nosec G101
+ HeaderReferrerPolicy = "Referrer-Policy"
+
+ // HeaderSecFetchSite fetch metadata request header indicates the relationship between a request initiator's
+ // origin and the origin of the requested resource.
+ // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site
+ HeaderSecFetchSite = "Sec-Fetch-Site"
+)const (
+ // NotFoundRouteName is name of RouteInfo returned when router did not find matching route (404: not found).
+ NotFoundRouteName = "echo_route_not_found_name"
+ // MethodNotAllowedRouteName is name of RouteInfo returned when router did not find matching method for route (405: method not allowed).
+ MethodNotAllowedRouteName = "echo_route_method_not_allowed_name"
+)const (
+ // ContextKeyHeaderAllow is set by Router for getting value for `Allow` header in later stages of handler call chain.
+ // Allow header is mandatory for status 405 (method not found) and useful for OPTIONS method requests.
+ // It is added to context only when Router does not find matching method handler for request.
+ ContextKeyHeaderAllow = "echo_header_allow"
+)const (
+ // Version of Echo
+ Version = "5.3.0"
+)The following errors can produce HTTP status code by implementing HTTPStatusCoder interface
var (
+ ErrBadRequest = &httpError{http.StatusBadRequest} // 400
+ ErrUnauthorized = &httpError{http.StatusUnauthorized} // 401
+ ErrForbidden = &httpError{http.StatusForbidden} // 403
+ ErrNotFound = &httpError{http.StatusNotFound} // 404
+ ErrMethodNotAllowed = &httpError{http.StatusMethodNotAllowed} // 405
+ ErrRequestTimeout = &httpError{http.StatusRequestTimeout} // 408
+ ErrStatusRequestEntityTooLarge = &httpError{http.StatusRequestEntityTooLarge} // 413
+ ErrUnsupportedMediaType = &httpError{http.StatusUnsupportedMediaType} // 415
+ ErrTooManyRequests = &httpError{http.StatusTooManyRequests} // 429
+ ErrInternalServerError = &httpError{http.StatusInternalServerError} // 500
+ ErrBadGateway = &httpError{http.StatusBadGateway} // 502
+ ErrServiceUnavailable = &httpError{http.StatusServiceUnavailable} // 503
+)The following errors fall into 500 (InternalServerError) category
var (
+ ErrValidatorNotRegistered = errors.New("validator not registered")
+ ErrRendererNotRegistered = errors.New("renderer not registered")
+ ErrInvalidRedirectCode = errors.New("invalid redirect status code")
+ ErrCookieNotFound = errors.New("cookie not found")
+ ErrInvalidCertOrKeyType = errors.New("invalid cert or key type, must be string or []byte")
+ ErrInvalidListenerNetwork = errors.New("invalid listener network")
+)ErrInvalidKeyType is error that is returned when the value is not castable to expected type.
var ErrInvalidKeyType = errors.New("invalid key type")ErrNonExistentKey is error that is returned when key does not exist
var ErrNonExistentKey = errors.New("non existent key")BindBody binds request body contents to bindable object +NB: then binding forms take note that this implementation uses standard library form parsing +which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm +See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm +See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm
BindHeaders binds HTTP headers to a bindable object
BindPathValues binds path parameter values to bindable object
BindQueryParams binds query params to bindable object
ContextGet retrieves a value from the context store or ErrNonExistentKey error the key is missing. +Returns ErrInvalidKeyType error if the value is not castable to type T.
ContextGetOr retrieves a value from the context store or returns a default value when the key +is missing. Returns ErrInvalidKeyType error if the value is not castable to type T.
DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response
+with status code. exposeError parameter decides if returned message will contain also error message or not
Note: DefaultHTTPErrorHandler does not log errors. Use middleware for it if errors need to be logged (separately) +Note: In case errors happens in middleware call-chain that is returning from handler (which did not return an error). +When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from +handler. Then the error that global error handler received will be ignored because we have already "committed" the +response and status code header has been sent to the client.
// SPDX-License-Identifier: MIT
+// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
+
+// run tests as external package to get real feel for API
+package echo_test
+
+import (
+ "encoding/json"
+ "fmt"
+ "github.com/labstack/echo/v5"
+ "net/http"
+ "net/http/httptest"
+)
+
+func ExampleDefaultHTTPErrorHandler() {
+ e := echo.New()
+ e.GET("/api/endpoint", func(c *echo.Context) error {
+ return &apiError{
+ Code: http.StatusBadRequest,
+ Body: map[string]any{"message": "custom error"},
+ }
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/endpoint?err=1", nil)
+ resp := httptest.NewRecorder()
+
+ e.ServeHTTP(resp, req)
+
+ fmt.Printf("%d %s", resp.Code, resp.Body.String())
+
+ // Output: 400 {"error":{"message":"custom error"}}
+}
+
+type apiError struct {
+ Code int
+ Body any
+}
+
+func (e *apiError) StatusCode() int {
+ return e.Code
+}
+
+func (e *apiError) MarshalJSON() ([]byte, error) {
+ type body struct {
+ Error any `json:"error"`
+ }
+ return json.Marshal(body{Error: e.Body})
+}
+
+func (e *apiError) Error() string {
+ return http.StatusText(e.Code)
+}
+Output:
+400 {"error":{"message":"custom error"}}ExtractIPDirect extracts an IP address using an actual IP address. +Use this if your server faces to internet directly (i.e.: uses no proxy).
ExtractIPFromRealIPHeader extracts IP address using x-real-ip header.
+Use this if you put proxy which uses this header.
ExtractIPFromXFFHeader extracts IP address using x-forwarded-for header.
+Use this if you put proxy which uses this header.
+This returns nearest untrustable IP. If all IPs are trustable, returns furthest one (i.e.: XFF[0]).
FormFieldBinder creates form field value binder +For all requests, FormFieldBinder parses the raw query from the URL and uses query params as form fields
+For POST, PUT, and PATCH requests, it also reads the request body, parses it +as a form and uses query params as form fields. Request body parameters take precedence over URL query +string values in r.Form.
+NB: when binding forms take note that this implementation uses standard library form parsing +which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm +See https://golang.org/pkg/net/http/#Request.ParseForm
FormValue extracts and parses a single form value from the request by key. +It returns the typed value and an error if binding fails. Returns ErrNonExistentKey if parameter not found.
+Empty String Handling:
+If the form field exists but has an empty value, the zero value of type T is returned
+with no error. For example, an empty form field returns (0, nil) for int types.
+This differs from standard library behavior where parsing empty strings returns errors.
+To treat empty values as errors, validate the result separately or check the raw value.See ParseValue for supported types and options
FormValueOr extracts and parses a single form value from the request by key. +Returns defaultValue if the parameter is not found or has an empty value. +Returns an error only if parsing fails or form parsing errors occur.
+Example:
+limit, err := echo.FormValueOr[int](c, "limit", 100)
+// If "limit" is missing: returns (100, nil)
+// If "limit" is "50": returns (50, nil)
+// If "limit" is "abc": returns (100, BindingError)See ParseValue for supported types and options
FormValues extracts and parses all values for a form values key as a slice. +It returns the typed slice and an error if binding any value fails. Returns ErrNonExistentKey if parameter not found.
+See ParseValues for supported types and options
FormValuesOr extracts and parses all values for a form values key as a slice. +Returns defaultValue if the parameter is not found. +Returns an error only if parsing any value fails or form parsing errors occur.
+Example:
+tags, err := echo.FormValuesOr[string](c, "tags", []string{})
+// If "tags" is missing: returns ([], nil)
+// If form parsing fails: returns (nil, error)See ParseValues for supported types and options
HandlerName returns string name for given function.
LegacyIPExtractor returns an IPExtractor that derives the client IP address +from common proxy headers, falling back to the request's remote address.
+Resolution order:
+Notes:
+Use ExtractIPFromXFFHeader or ExtractIPFromRealIPHeader instead of LegacyIPExtractor.
MustSubFS creates sub FS from current filesystem or panic on failure.
+Panic happens when fsRoot contains invalid path according to fs.ValidPath rules.
MustSubFS is helpful when dealing with embed.FS because for example //go:embed assets/images embeds files with
+paths including assets/images as their prefix. In that case use `fs := echo.MustSubFS(fs, "rootDirectory") to
+create sub fs which uses necessary prefix for directory path.
New creates an instance of Echo.
NewBindingError creates new instance of binding error
Source: router_concurrent.go:9
+NewConcurrentRouter creates concurrency safe Router which routes can be added/removed safely +even after http.Server has been started.
NewContext returns a new Context instance.
+Note: request,response and e can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway +these arguments are useful when creating context for tests and cases like that.
NewDefaultFS returns a new defaultFS instance which allows fs.FS.Open to have absolute paths as input if it matches
+then given dir as prefix.
NewHTTPError creates a new instance of HTTPError
NewResponse creates a new instance of Response.
NewRouter returns a new Router instance.
NewVirtualHostHandler creates instance of Echo that routes requests to given virtual hosts +when hosts in request does not exist in given map the request is served by returned Echo instance.
NewWithConfig creates an instance of Echo with given configuration.
ParseValue parses value to generic type
+Types that are supported:
+ParseValueOr parses value to generic type, when value is empty defaultValue is returned.
+Types that are supported:
+ParseValues parses value to generic type slice. Same types are supported as ParseValue +function but the result type is slice instead of scalar value.
+See ParseValue for supported types and options
ParseValuesOr parses value to generic type slice, when value is empty defaultValue is returned. +Same types are supported as ParseValue function but the result type is slice instead of scalar value.
+See ParseValue for supported types and options
PathParam extracts and parses a path parameter from the context by name. +It returns the typed value and an error if binding fails. Returns ErrNonExistentKey if parameter not found.
+Empty String Handling:
+If the parameter exists but has an empty value, the zero value of type T is returned
+with no error. For example, a path parameter with value "" returns (0, nil) for int types.
+This differs from standard library behavior where parsing empty strings returns errors.
+To treat empty values as errors, validate the result separately or check the raw value.See ParseValue for supported types and options
PathParamOr extracts and parses a path parameter from the context by name. +Returns defaultValue if the parameter is not found or has an empty value. +Returns an error only if parsing fails (e.g., "abc" for int type).
+Example:
+id, err := echo.PathParamOr[int](c, "id", 0)
+// If "id" is missing: returns (0, nil)
+// If "id" is "123": returns (123, nil)
+// If "id" is "abc": returns (0, BindingError)See ParseValue for supported types and options
PathValuesBinder creates path parameter value binder
QueryParam extracts and parses a single query parameter from the request by key. +It returns the typed value and an error if binding fails. Returns ErrNonExistentKey if parameter not found.
+Empty String Handling:
+If the parameter exists but has an empty value (?key=), the zero value of type T is returned
+with no error. For example, "?count=" returns (0, nil) for int types.
+This differs from standard library behavior where parsing empty strings returns errors.
+To treat empty values as errors, validate the result separately or check the raw value.Behavior Summary:
+See ParseValue for supported types and options
QueryParamOr extracts and parses a single query parameter from the request by key. +Returns defaultValue if the parameter is not found or has an empty value. +Returns an error only if parsing fails (e.g., "abc" for int type).
+Example:
+page, err := echo.QueryParamOr[int](c, "page", 1)
+// If "page" is missing: returns (1, nil)
+// If "page" is "5": returns (5, nil)
+// If "page" is "abc": returns (1, BindingError)See ParseValue for supported types and options
QueryParams extracts and parses all values for a query parameter key as a slice. +It returns the typed slice and an error if binding any value fails. Returns ErrNonExistentKey if parameter not found.
+See ParseValues for supported types and options
QueryParamsBinder creates query parameter value binder
QueryParamsOr extracts and parses all values for a query parameter key as a slice. +Returns defaultValue if the parameter is not found. +Returns an error only if parsing any value fails.
+Example:
+ids, err := echo.QueryParamsOr[int](c, "ids", []int{})
+// If "ids" is missing: returns ([], nil)
+// If "ids" is "1&ids=2": returns ([1, 2], nil)
+// If "ids" contains "abc": returns ([], BindingError)See ParseValues for supported types and options
ResolveResponseStatus returns the Response and HTTP status code that should be (or has been) sent for rw, +given an optional error.
+This function is useful for middleware and handlers that need to figure out the HTTP status +code to return based on the error that occurred or what was set in the response.
+Precedence rules:
+StaticDirectoryHandler creates handler function to serve files from provided file system +When disablePathUnescaping is set then file name from path is not unescaped and is served as is.
+Note: when disablePathUnescaping=false, the handler decodes the wildcard param before serving. +If route guards (e.g. e.GET("/admin/*", forbidden)) are used to restrict parts of the +filesystem, an encoded separator (%2F) or encoded dot-dot (%2E%2E) in the URL can resolve to +a path that the router never matched against the guard route. Enabling +RouterConfig.UseEscapedPathForMatching does NOT fix this — it changes which path the router +uses for matching but still lets path.Clean resolve ".." segments into a guarded directory. +Do not rely on route guards alone to restrict a filesystem served by this handler. +See https://github.com/labstack/echo/security/advisories/GHSA-vfp3-v2gw-7wfq
StaticFileHandler creates handler function to serve file from provided file system.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
StatusCode returns status code from err if it implements HTTPStatusCoder interface. +If err does not implement the interface, it returns 0.
TrustIPRange add trustable IP ranges using CIDR notation.
TrustLinkLocal configures if you trust link-local address (default: true).
TrustLoopback configures if you trust loopback address (default: true).
TrustPrivateNet configures if you trust private network address (default: true).
UnwrapResponse unwraps given ResponseWriter to return contexts original Echo Response. rw has to implement
+following method Unwrap() http.ResponseWriter
WrapHandler wraps http.Handler into echo.HandlerFunc.
WrapMiddleware wraps func(http.Handler) http.Handler into echo.MiddlewareFunc
AddRouteError is error returned by Router.Add containing information what actual route adding failed. Useful for +mass adding (i.e. Any() routes)
type AddRouteError struct {
+ Err error
+ Method string
+ Path string
+}Err error Method string Path string BindUnmarshaler is the interface used to wrap the UnmarshalParam method. +Types that don't implement this, but do implement encoding.TextUnmarshaler +will use that interface instead.
type BindUnmarshaler interface {
+ // UnmarshalParam decodes and assigns a value from an form or query param.
+ UnmarshalParam(param string) error
+}UnmarshalParam func(param string) error UnmarshalParam decodes and assigns a value from an form or query param.
Binder is the interface that wraps the Bind method.
type Binder interface {
+ Bind(c *Context, target any) error
+}Bind func(c *Context, target any) error BindingError represents an error that occurred while binding request data.
+Note: JSON serialization is handled by the MarshalJSON method below, not by the +struct tags (which are kept for documentation). MarshalJSON emits {"field","message"}.
type BindingError struct {
+ // Field is the field name where value binding failed
+ Field string `json:"field"`
+ *HTTPError
+ // Values of parameter that failed to bind.
+ Values []string `json:"-"`
+}Field string `json:"field"`Field is the field name where value binding failed
*HTTPError Values []string `json:"-"`Values of parameter that failed to bind.
Error returns error message
MarshalJSON implements json.Marshaler so that binding errors are serialized into +a structured response (e.g. {"field":"id","message":"..."}) rather than being +flattened to a generic message. DefaultHTTPErrorHandler routes errors that +implement json.Marshaler through their own encoding.
Config is configuration for NewWithConfig function
type Config struct {
+ // Logger is the slog logger instance used for application-wide structured logging.
+ // If not set, a default TextHandler writing to stdout is created.
+ Logger *slog.Logger
+
+ // HTTPErrorHandler is the centralized error handler that processes errors returned
+ // by handlers and middleware, converting them to appropriate HTTP responses.
+ // If not set, DefaultHTTPErrorHandler(false) is used.
+ HTTPErrorHandler HTTPErrorHandler
+
+ // Router is the HTTP request router responsible for matching URLs to handlers
+ // using a radix tree-based algorithm.
+ // If not set, NewRouter(RouterConfig{}) is used.
+ Router Router
+
+ // OnAddRoute is an optional callback hook executed when routes are registered.
+ // Useful for route validation, logging, or custom route processing.
+ // If not set, no callback is executed.
+ OnAddRoute func(route Route) error
+
+ // Filesystem is the fs.FS implementation used for serving static files.
+ // Supports os.DirFS, embed.FS, and custom implementations.
+ // If not set, defaults to current working directory.
+ Filesystem fs.FS
+
+ // Binder handles automatic data binding from HTTP requests to Go structs.
+ // Supports JSON, XML, form data, query parameters, and path parameters.
+ // If not set, DefaultBinder is used.
+ Binder Binder
+
+ // Validator provides optional struct validation after data binding.
+ // Commonly used with third-party validation libraries.
+ // If not set, Context.Validate() returns ErrValidatorNotRegistered.
+ Validator Validator
+
+ // Renderer provides template rendering for generating HTML responses.
+ // Requires integration with a template engine like html/template.
+ // If not set, Context.Render() returns ErrRendererNotRegistered.
+ Renderer Renderer
+
+ // JSONSerializer handles JSON encoding and decoding for HTTP requests/responses.
+ // Can be replaced with faster alternatives like jsoniter or sonic.
+ // If not set, DefaultJSONSerializer using encoding/json is used.
+ JSONSerializer JSONSerializer
+
+ // IPExtractor defines the strategy for extracting the real client IP address
+ // from requests, particularly important when behind proxies or load balancers.
+ // Used for rate limiting, access control, and logging.
+ // If not set, falls back to checking X-Forwarded-For and X-Real-IP headers.
+ IPExtractor IPExtractor
+
+ // FormParseMaxMemory is default value for memory limit that is used
+ // when parsing multipart forms (See (*http.Request).ParseMultipartForm)
+ FormParseMaxMemory int64
+
+ // EnablePathUnescapingStaticFiles enables path parameter (param: *) unescaping for static file methods.
+ // Default false (safe): encoded slashes (%2f) in the wildcard param are NOT decoded,
+ // preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/* route guard by
+ // not matching that route but having its wildcard param decoded to admin/private.txt.
+ // Set to true only when serving files whose names contain URL-encoded characters
+ // (e.g. "hello world.txt" via /hello%20world.txt) and you are not relying on
+ // route-based ACL guards to restrict access.
+ // If you are enabling this option, make sure you understand the security implications.
+ // See: https://github.com/labstack/echo/security/advisories/GHSA-vfp3-v2gw-7wfq
+ //
+ // Enabling RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when
+ // using different Routes to exclude some of the files from being served.
+ // e.g. if you serve files from directory as such and use different route to exclude some of the files from being served.
+ // 0. given folder structure:
+ // public/
+ // public/index.html
+ // public/admin/private.txt
+ // 1. share `public/` folder contents from the server root with `e.Static("/", "public")`
+ // 2. naively assume that everything under /admin folder is now forbidden
+ // e.GET("/admin/*", func(c *Context) error { return echo.ErrForbidden })
+ // Then request to `/assets/../admin%2fprivate.txt` will be served as router does not match it to guarded route.
+ //
+ // Applies to methods: Echo.Static, Echo.StaticFS, Group.Static, Group.StaticFS.
+ EnablePathUnescapingStaticFiles bool
+
+ // NoGroupAutoRegister404Routes bool is a flag that indicates whether echo.Group should NOT register 404 routes automatically
+ // when there are middlewares registered with the group.
+ // Note: if you decide not to register 404 routes automatically, make sure to check if all your middlewares are executed
+ // as expected. For example - CORS middleware.
+ NoGroupAutoRegister404Routes bool
+}Logger *slog.Logger Logger is the slog logger instance used for application-wide structured logging. +If not set, a default TextHandler writing to stdout is created.
HTTPErrorHandler HTTPErrorHandler HTTPErrorHandler is the centralized error handler that processes errors returned +by handlers and middleware, converting them to appropriate HTTP responses. +If not set, DefaultHTTPErrorHandler(false) is used.
Router Router Router is the HTTP request router responsible for matching URLs to handlers +using a radix tree-based algorithm. +If not set, NewRouter(RouterConfig{}) is used.
OnAddRoute func(route Route) error OnAddRoute is an optional callback hook executed when routes are registered. +Useful for route validation, logging, or custom route processing. +If not set, no callback is executed.
Filesystem fs.FS Filesystem is the fs.FS implementation used for serving static files. +Supports os.DirFS, embed.FS, and custom implementations. +If not set, defaults to current working directory.
Binder Binder Binder handles automatic data binding from HTTP requests to Go structs. +Supports JSON, XML, form data, query parameters, and path parameters. +If not set, DefaultBinder is used.
Validator Validator Validator provides optional struct validation after data binding. +Commonly used with third-party validation libraries. +If not set, Context.Validate() returns ErrValidatorNotRegistered.
Renderer Renderer Renderer provides template rendering for generating HTML responses. +Requires integration with a template engine like html/template. +If not set, Context.Render() returns ErrRendererNotRegistered.
JSONSerializer JSONSerializer JSONSerializer handles JSON encoding and decoding for HTTP requests/responses. +Can be replaced with faster alternatives like jsoniter or sonic. +If not set, DefaultJSONSerializer using encoding/json is used.
IPExtractor IPExtractor IPExtractor defines the strategy for extracting the real client IP address +from requests, particularly important when behind proxies or load balancers. +Used for rate limiting, access control, and logging. +If not set, falls back to checking X-Forwarded-For and X-Real-IP headers.
FormParseMaxMemory int64 FormParseMaxMemory is default value for memory limit that is used +when parsing multipart forms (See (*http.Request).ParseMultipartForm)
EnablePathUnescapingStaticFiles bool EnablePathUnescapingStaticFiles enables path parameter (param: ) unescaping for static file methods. +Default false (safe): encoded slashes (%2f) in the wildcard param are NOT decoded, +preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/ route guard by +not matching that route but having its wildcard param decoded to admin/private.txt. +Set to true only when serving files whose names contain URL-encoded characters +(e.g. "hello world.txt" via /hello%20world.txt) and you are not relying on +route-based ACL guards to restrict access. +If you are enabling this option, make sure you understand the security implications. +See: https://github.com/labstack/echo/security/advisories/GHSA-vfp3-v2gw-7wfq
+Enabling RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when +using different Routes to exclude some of the files from being served. +e.g. if you serve files from directory as such and use different route to exclude some of the files from being served. +0. given folder structure: + public/ + public/index.html + public/admin/private.txt
+public/ folder contents from the server root with e.Static("/", "public")/assets/../admin%2fprivate.txt will be served as router does not match it to guarded route.Applies to methods: Echo.Static, Echo.StaticFS, Group.Static, Group.StaticFS.
NoGroupAutoRegister404Routes bool NoGroupAutoRegister404Routes bool is a flag that indicates whether echo.Group should NOT register 404 routes automatically +when there are middlewares registered with the group. +Note: if you decide not to register 404 routes automatically, make sure to check if all your middlewares are executed +as expected. For example - CORS middleware.
Context represents the context of the current HTTP request. It holds request and +response objects, path, path parameters, data and registered handler.
type Context struct {
+ // contains filtered or unexported fields
+}Attachment sends a response as attachment, prompting client to save the file.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
Bind binds path params, query params and the request body into provided type i. The default binder
+binds body based on Content-Type header.
Blob sends a blob response with status code and content type.
Cookie returns the named cookie provided in the request.
Cookies returns the HTTP cookies sent with the request.
Echo returns the Echo instance.
File sends a response with the content of the file.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
FileFS serves file from given file system.
+When dealing with embed.FS use fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path. This is necessary as //go:embed assets/imagesembeds files with paths includingassets/images` as their prefix.
FormFile returns the multipart form file for the provided name.
FormValue returns the form field value for the provided name.
FormValueOr returns the form field value or default value for the provided name. +Note: FormValueOr does not distinguish if form had no value by that name or value was empty string
FormValues returns the form field values as url.Values.
Get retrieves data from the context. +Method returns any(nil) when key does not exist which is different from typed nil (eg. []byte(nil)).
HTML sends an HTTP response with status code.
HTMLBlob sends an HTTP blob response with status code.
InitializeRoute sets the route related variables of this request to the context.
Inline sends a response as inline, opening the file in the browser.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
IsTLS returns true if HTTP connection is TLS otherwise false.
IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
JSON sends a JSON response with status code.
JSONBlob sends a JSON blob response with status code.
JSONP sends a JSONP response with status code. It uses callback to construct
+the JSONP payload.
JSONPBlob sends a JSONP blob response with status code. It uses callback
+to construct the JSONP payload.
JSONPretty sends a pretty-print JSON with status code.
Logger returns logger in Context
MultipartForm returns the multipart form.
NoContent sends a response with no body and a status code.
Param returns path parameter by name.
ParamOr returns the path parameter or default value for the provided name.
+Notes for DefaultRouter implementation: +Path parameter could be empty for cases like that:
+/release-:version/bin and request URL is /release-/bin/api/:version/image.jpg and request URL is /api//image.jpg
+but not when path parameter is last part of route path/download/file.:ext will not match request /download/file.Path returns the registered path for the handler.
PathValues returns path parameter values.
QueryParam returns the query param for the provided name.
QueryParamOr returns the query param or default value for the provided name.
+Note: QueryParamOr does not distinguish if query had no value by that name or value was empty string
+This means URLs /test?search= and /test would both return 1 for c.QueryParamOr("search", "1")
QueryParams returns the query parameters as url.Values.
QueryString returns the URL query string.
RealIP returns the client IP address using the configured extraction strategy.
+If Echo#IPExtractor is set, it is used to resolve the client IP from the incoming request (typically via proxy
+headers such as X-Forwarded-For or X-Real-IP).
+Look into the ip.go file for comments and examples.
See:
+X-Forwarded-For handling with trust checksX-Real-IP handling with trust checksv4 compatibility (spoofable, no trust checks built in)If no extractor is configured, RealIP falls back to the request RemoteAddr, returning only the host portion.
+Notes:
+Redirect redirects the request to a provided URL with status code.
Render renders a template with data and sends a text/html response with status
+code. Renderer must be registered using Echo.Renderer.
Request returns *http.Request.
Reset resets the context after request completes. It must be called along
+with Echo#AcquireContext() and Echo#ReleaseContext().
+See Echo#ServeHTTP()
Response returns *Response.
RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route.
+RouteInfo returns generic "empty" struct for these cases:
+e.Pre())Scheme returns the HTTP protocol scheme, http or https.
Set saves data in the context.
SetCookie adds a Set-Cookie header in HTTP response.
SetLogger sets logger in Context
SetPath sets the registered path for the handler.
SetPathValues sets path parameters for current request.
SetRequest sets *http.Request.
SetResponse sets *http.ResponseWriter. Some context methods and/or middleware require that given ResponseWriter implements following
+method Unwrap() http.ResponseWriter which eventually should return *echo.Response instance.
Stream sends a streaming response with status code and content type.
String sends a string response with status code.
Validate validates provided i. It is usually called after Context#Bind().
+Validator must be registered using Echo#Validator.
XML sends an XML response with status code.
XMLBlob sends an XML blob response with status code.
XMLPretty sends a pretty-print XML with status code.
DefaultBinder is the default implementation of the Binder interface.
type DefaultBinder struct{}Bind implements the Binder#Bind function.
+Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous
+step bound values. For single source binding use their own methods BindBody, BindQueryParams, BindPathValues.
DefaultJSONSerializer implements JSON encoding using encoding/json.
type DefaultJSONSerializer struct{}Deserialize reads a JSON from a request body and converts it into an interface.
+The body is read into a pooled buffer and decoded with json.Unmarshal rather +than streaming through json.NewDecoder. This avoids allocating a decoder and +its internal read buffer on every request. json.Unmarshal does not retain a +reference to the input slice, so the buffer is safe to reuse afterwards.
+Note: the full request body is read into memory before decoding. As with any +JSON parser, decoding untrusted input can allocate large amounts of memory; +guard such endpoints with middleware.BodyLimit (or http.MaxBytesReader), +which makes the body read here fail fast once the limit is exceeded.
Serialize converts an interface into a json and writes it to the response. +You can optionally use the indent parameter to produce pretty JSONs.
DefaultRouter is the registry of all registered routes for an Echo instance for
+request matching and URL path parameter parsing.
+Note: DefaultRouter is not coroutine-safe. Do not Add/Remove routes after HTTP server has been started with Echo.
type DefaultRouter struct {
+ // contains filtered or unexported fields
+}Add registers a new route for method and path with matching handler.
Remove unregisters registered route
Route looks up a handler registered for method and path. It also parses URL for path parameters and loads them +into context.
+For performance:
+Echo#AcquireContext()Context#Reset()Echo#ReleaseContext().Routes returns all registered routes
Echo is the top-level framework instance.
+Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these +fields from handlers/middlewares and changing field values at the same time leads to data-races. +Same rule applies to adding new routes after server has been started - Adding a route is not Goroutine safe action.
type Echo struct {
+ Binder Binder
+
+ // Filesystem is the file system used for serving static files. Defaults to the current working directory (os.Getwd()).
+ //
+ // Note: fs.FS.Open() already assumes that file names are relative to FS root path and considers name with prefix `/` as invalid
+ // so if you have `fs := os.DirFS("/tmp")` and you try to `fs.Open("/tmp/file.txt")` it will fail, but "file.txt"
+ // would succeed. `echo.NewDefaultFS("/tmp")` overwrites this behavior and allows you to use Open with a matching
+ // absolute path prefix.
+ Filesystem fs.FS
+
+ Renderer Renderer
+ Validator Validator
+ JSONSerializer JSONSerializer
+ IPExtractor IPExtractor
+ OnAddRoute func(route Route) error
+ HTTPErrorHandler HTTPErrorHandler
+ Logger *slog.Logger
+ // contains filtered or unexported fields
+}Binder Binder Filesystem fs.FS Filesystem is the file system used for serving static files. Defaults to the current working directory (os.Getwd()).
+Note: fs.FS.Open() already assumes that file names are relative to FS root path and considers name with prefix / as invalid
+so if you have fs := os.DirFS("/tmp") and you try to fs.Open("/tmp/file.txt") it will fail, but "file.txt"
+would succeed. echo.NewDefaultFS("/tmp") overwrites this behavior and allows you to use Open with a matching
+absolute path prefix.
Renderer Renderer Validator Validator JSONSerializer JSONSerializer IPExtractor IPExtractor OnAddRoute func(route Route) error HTTPErrorHandler HTTPErrorHandler Logger *slog.Logger AcquireContext returns an empty Context instance from the pool.
+You must return the context by calling ReleaseContext().
Add registers a new route for an HTTP method and path with matching handler +in the router with optional route-level middleware.
AddRoute registers a new Route with default host Router
Any registers a new route for all HTTP methods (supported by Echo) and path with matching handler +in the router with optional route-level middleware.
+Note: this method only adds specific set of supported HTTP methods as handler and is not true +"catch-any-arbitrary-method" way of matching requests.
CONNECT registers a new CONNECT route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
DELETE registers a new DELETE route for a path with matching handler in the router +with optional route-level middleware. Panics on error.
File registers a new route with path to serve a static file with optional route-level middleware. Panics on error.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
FileFS registers a new route with path to serve file from the provided file system.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
GET registers a new GET route for a path with matching handler in the router +with optional route-level middleware. Panics on error.
Group creates a new router group with prefix and optional group-level middleware.
HEAD registers a new HEAD route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
Match registers a new route for multiple HTTP methods and path with matching +handler in the router with optional route-level middleware. Panics on error.
Middlewares returns registered route level middlewares. Does not contain any group level +middlewares. Use this method to build your own ServeHTTP method.
+NOTE: returned slice is not a copy. Do not mutate.
NewContext returns a new Context instance.
+Note: both request and response can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway +these arguments are useful when creating context for tests and cases like that.
OPTIONS registers a new OPTIONS route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
PATCH registers a new PATCH route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
POST registers a new POST route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
PUT registers a new PUT route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
Pre adds middleware to the chain which is run before router tries to find matching route. +Meaning middleware is executed even for 404 (not found) cases.
PreMiddlewares returns registered pre middlewares. These are middleware to the chain +which are run before router tries to find matching route. +Use this method to build your own ServeHTTP method.
+NOTE: returned slice is not a copy. Do not mutate.
QUERY registers a new QUERY route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
ReleaseContext returns the Context instance back to the pool.
+You must call it after AcquireContext().
RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases)
+for current request URL.
+Path supports static and named/any parameters just like other http method is defined. Generally path is ended with
+wildcard/match-any character (/*, /download/* etc).
Example: e.RouteNotFound("/*", func(c *echo.Context) error { return c.NoContent(http.StatusNotFound) })
Router returns the default router.
ServeHTTP implements http.Handler interface, which serves HTTP requests.
Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by
+sending os.Interrupt signal with ctrl+c. Method returns only errors that are not http.ErrServerClosed.
Note: this method is created for use in examples/demos and is deliberately simple without providing configuration +options.
+In need of customization use:
+ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+defer cancel()
+sc := echo.StartConfig{Address: ":8080"}
+if err := sc.Start(ctx, e); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ slog.Error(err.Error())
+}// or standard library http.Server
s := http.Server{Addr: ":8080", Handler: e}
+if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ slog.Error(err.Error())
+}Static registers a new route with path prefix to serve static files from the provided root directory.
StaticFS registers a new route with path prefix to serve static files from the provided file system.
+When dealing with embed.FS use fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path. This is necessary as //go:embed assets/imagesembeds files with paths includingassets/images` as their prefix.
TRACE registers a new TRACE route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed.
Group is a set of sub-routes for a specified route. It can be used for inner +routes that share a common middleware or functionality that should be separate +from the parent echo instance while still inheriting from it.
type Group struct {
+ // contains filtered or unexported fields
+}Add implements Echo#Add() for sub-routes within the Group. Panics on error.
AddRoute registers a new Routable with Router
Any implements Echo#Any() for sub-routes within the Group. Panics on error.
CONNECT implements Echo#CONNECT() for sub-routes within the Group. Panics on error.
DELETE implements Echo#DELETE() for sub-routes within the Group. Panics on error.
File implements Echo#File() for sub-routes within the Group. Panics on error.
Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
FileFS implements Echo#FileFS() for sub-routes within the Group.
Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
GET implements Echo#GET() for sub-routes within the Group. Panics on error.
Group creates a new sub-group with prefix and optional sub-group-level middleware.
+Important! Group middlewares are executed in case there was no exact route match as by default Group registers
+/* NotFound routes for itself. If this kind of behavior is not needed, then create an Echo instance with the noAutoRegisterRoutes
+flag set to true. Example echo.NewWithConfig(echo.Config{NoGroupAutoRegister404Routes: true}).
HEAD implements Echo#HEAD() for sub-routes within the Group. Panics on error.
Match implements Echo#Match() for sub-routes within the Group. Panics on error.
OPTIONS implements Echo#OPTIONS() for sub-routes within the Group. Panics on error.
PATCH implements Echo#PATCH() for sub-routes within the Group. Panics on error.
POST implements Echo#POST() for sub-routes within the Group. Panics on error.
PUT implements Echo#PUT() for sub-routes within the Group. Panics on error.
QUERY implements Echo#QUERY() for sub-routes within the Group. Panics on error.
RouteNotFound implements Echo#RouteNotFound() for sub-routes within the Group.
Example: g.RouteNotFound("/*", func(c *echo.Context) error { return c.NoContent(http.StatusNotFound) })
Static implements Echo#Static() for sub-routes within the Group.
StaticFS implements Echo#StaticFS() for sub-routes within the Group.
When dealing with embed.FS use fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path. This is necessary as //go:embed assets/imagesembeds files with paths includingassets/images` as their prefix.
TRACE implements Echo#TRACE() for sub-routes within the Group. Panics on error.
Use implements Echo#Use() for sub-routes within the Group.
Important! Group middlewares are executed in case there was no exact route match as by default Group registers
+/* NotFound routes for itself. If this kind of behavior is not needed, then create an Echo instance with the noAutoRegisterRoutes
+flag set to true. Example echo.NewWithConfig(echo.Config{NoGroupAutoRegister404Routes: true}).
HTTPError represents an error that occurred while handling a request.
type HTTPError struct {
+ // Code is status code for HTTP response
+ Code int `json:"-"`
+ Message string `json:"message"`
+ // contains filtered or unexported fields
+}Code int `json:"-"`Code is status code for HTTP response
Message string `json:"message"`Error makes it compatible with the error interface.
StatusCode returns status code for HTTP response
Wrap returns a new HTTPError with given errors wrapped inside
HTTPErrorHandler is a centralized HTTP error handler.
type HTTPErrorHandler func(c *Context, err error)HTTPStatusCoder is an interface that errors can implement to produce status code for HTTP response
type HTTPStatusCoder interface {
+ StatusCode() int
+}StatusCode func() int HandlerFunc defines a function to serve HTTP requests.
type HandlerFunc func(c *Context) errorIPExtractor is a function to extract IP addr from http.Request. +Set appropriate one to Echo#IPExtractor. +See https://echo.labstack.com/guide/ip-address for more details.
type IPExtractor func(*http.Request) stringJSONSerializer is the interface that encodes and decodes JSON to and from interfaces.
type JSONSerializer interface {
+ Serialize(c *Context, target any, indent string) error
+ Deserialize(c *Context, target any) error
+}Serialize func(c *Context, target any, indent string) error Deserialize func(c *Context, target any) error MiddlewareConfigurator defines interface for creating middleware handlers with possibility to return configuration errors instead of panicking.
type MiddlewareConfigurator interface {
+ ToMiddleware() (MiddlewareFunc, error)
+}ToMiddleware func() (MiddlewareFunc, error) MiddlewareFunc defines a function to process middleware.
type MiddlewareFunc func(next HandlerFunc) HandlerFuncPathValue is tuple pf path parameter name and its value in request path
type PathValue struct {
+ Name string
+ Value string
+}Name string Value string PathValues is collections of PathValue instances with various helper methods
type PathValues []PathValueGet returns path parameter value for given name or false.
GetOr returns path parameter value for given name or default value if the name does not exist.
Renderer is the interface that wraps the Render function.
type Renderer interface {
+ Render(c *Context, w io.Writer, templateName string, data any) error
+}Render func(c *Context, w io.Writer, templateName string, data any) error Response wraps an http.ResponseWriter and implements its interface to be used +by an HTTP handler to construct an HTTP response. +See: https://golang.org/pkg/net/http/#ResponseWriter
type Response struct {
+ http.ResponseWriter
+
+ Status int
+ Size int64
+ Committed bool
+ // contains filtered or unexported fields
+}http.ResponseWriter Status int Size int64 Committed bool After registers a function which is called just after the response is written.
Before registers a function which is called just before the response (status) is written.
Flush implements the http.Flusher interface to allow an HTTP handler to flush +buffered data to the client. +See http.Flusher
Hijack implements the http.Hijacker interface to allow an HTTP handler to +take over the connection. +This method is relevant to Websocket connection upgrades, proxis, and other advanced use cases. +See http.Hijacker
Unwrap returns the original http.ResponseWriter. +ResponseController can be used to access the original http.ResponseWriter. +See [https://go.dev/blog/go1.20]
Write writes the data to the connection as part of an HTTP reply.
WriteHeader sends an HTTP response header with status code. If WriteHeader is +not called explicitly, the first call to Write will trigger an implicit +WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly +used to send error codes.
Route contains information to adding/registering new route with the router. +Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path fields.
type Route struct {
+ Method string
+ Path string
+ Name string
+
+ // HandlerFunc is a function that handles HTTP requests. This could be left nil when the Router implementation allows
+ // fallback to default/global handlers in certain situations.
+ Handler HandlerFunc
+ Middlewares []MiddlewareFunc
+}Method string Path string Name string Handler HandlerFunc HandlerFunc is a function that handles HTTP requests. This could be left nil when the Router implementation allows +fallback to default/global handlers in certain situations.
Middlewares []MiddlewareFunc ToRouteInfo converts Route to RouteInfo
WithPrefix recreates Route with added group prefix and group middlewares it is grouped to.
RouteInfo contains information about registered Route.
type RouteInfo struct {
+ Name string
+ Method string
+ Path string
+ Parameters []string
+}Name string Method string Path string Parameters []string Clone creates copy of RouteInfo
Reverse reverses route to URL string by replacing path parameters with given params values.
Router is interface for routing request contexts to registered routes.
+Contract between Echo/Context instance and the router:
+Echo.contextPathParamAllocSize).type Router interface {
+ // Add registers Routable with the Router and returns registered RouteInfo.
+ //
+ // Router may change Route.Path value in returned RouteInfo.Path.
+ // Router generates RouteInfo.Parameters values from Route.Path.
+ // Router generates RouteInfo.Name value if it is not provided.
+ Add(routable Route) (RouteInfo, error)
+
+ // Remove removes route from the Router.
+ //
+ // Router may choose not to implement this method.
+ Remove(method string, path string) error
+
+ // Routes returns information about all registered routes
+ Routes() Routes
+
+ // Route searches Router for matching route and applies it to the given context. In case when no matching method
+ // was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404
+ // handler function.
+ //
+ // Router must populate Context during Router.Route call with:
+ // - Context.InitializeRoute() (IMPORTANT! to reduce allocations use same slice that c.PathValues() returns)
+ // - optionally can set additional information to Context with Context.Set()
+ Route(c *Context) HandlerFunc
+}Add func(routable Route) (RouteInfo, error) Add registers Routable with the Router and returns registered RouteInfo.
+Router may change Route.Path value in returned RouteInfo.Path. +Router generates RouteInfo.Parameters values from Route.Path. +Router generates RouteInfo.Name value if it is not provided.
Remove func(method string, path string) error Remove removes route from the Router.
+Router may choose not to implement this method.
Routes func() Routes Routes returns information about all registered routes
Route func(c *Context) HandlerFunc Route searches Router for matching route and applies it to the given context. In case when no matching method +was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 +handler function.
+Router must populate Context during Router.Route call with:
+RouterConfig is configuration options for (default) router
type RouterConfig struct {
+ // NotFoundHandler is a handler that is executed when no route matches the request.
+ NotFoundHandler HandlerFunc
+
+ // MethodNotAllowedHandler is a handler that is executed when no route with exact METHOD matches the request but
+ // there is a route with same path but different method.
+ MethodNotAllowedHandler HandlerFunc
+
+ // OptionsMethodHandler is a handler that is executed when an OPTIONS request is made.
+ OptionsMethodHandler HandlerFunc
+
+ // AllowOverwritingRoute allows overwriting existing routes. If false, then adding a route with the same method
+ // and path will return an error.
+ AllowOverwritingRoute bool
+
+ // UnescapePathParamValues forces router to unescape path parameter values before setting them in context.
+ UnescapePathParamValues bool
+
+ // UseEscapedPathForMatching forces router to use an escaped path (req.URL.RawPath instead of req.URL.Path) for matching.
+ // Difference between URL.RawPath and URL.Path is:
+ // * URL.Path is where request path is stored. Value is stored in decoded form: /%47%6f%2f becomes /Go/.
+ // * URL.RawPath is an optional field which only gets set if the default encoding is different from Path.
+ UseEscapedPathForMatching bool
+
+ // AutoHandleHEAD enables automatic handling of HTTP HEAD requests by
+ // falling back to the corresponding GET route.
+ //
+ // When enabled, a HEAD request will match the same handler as GET for
+ // the route, but the response body is suppressed in accordance with
+ // HTTP semantics. Headers (e.g., Content-Length, Content-Type) are
+ // preserved as if a GET request was made.
+ //
+ // Security considerations: the GET handler is fully executed for every
+ // HEAD request, including all side effects:
+ // - State-mutating operations (DB writes, audit logs, counters) run.
+ // - Rate-limiting middleware consumes quota, enabling low-cost exhaustion.
+ // - Expensive computations run with no response body returned to the
+ // caller, making HEAD cheaper to abuse for DoS than GET.
+ // - All GET routes become enumerable via HEAD probing (200 = route
+ // exists, 405 = route absent).
+ //
+ // If route confidentiality/state-mutation is a concern, leave AutoHandleHEAD disabled
+ // and register explicit HEAD handlers only for routes that are safe to
+ // expose (e.g. e.HEAD("/public", handler)).
+ // You can leverage Echo.OnAddRoute callback to add HEAD routes explicitly from a single place.
+ //
+ // Disabled by default.
+ AutoHandleHEAD bool
+}NotFoundHandler HandlerFunc NotFoundHandler is a handler that is executed when no route matches the request.
MethodNotAllowedHandler HandlerFunc MethodNotAllowedHandler is a handler that is executed when no route with exact METHOD matches the request but +there is a route with same path but different method.
OptionsMethodHandler HandlerFunc OptionsMethodHandler is a handler that is executed when an OPTIONS request is made.
AllowOverwritingRoute bool AllowOverwritingRoute allows overwriting existing routes. If false, then adding a route with the same method +and path will return an error.
UnescapePathParamValues bool UnescapePathParamValues forces router to unescape path parameter values before setting them in context.
UseEscapedPathForMatching bool UseEscapedPathForMatching forces router to use an escaped path (req.URL.RawPath instead of req.URL.Path) for matching. +Difference between URL.RawPath and URL.Path is:
+AutoHandleHEAD bool AutoHandleHEAD enables automatic handling of HTTP HEAD requests by +falling back to the corresponding GET route.
+When enabled, a HEAD request will match the same handler as GET for +the route, but the response body is suppressed in accordance with +HTTP semantics. Headers (e.g., Content-Length, Content-Type) are +preserved as if a GET request was made.
+Security considerations: the GET handler is fully executed for every +HEAD request, including all side effects:
+If route confidentiality/state-mutation is a concern, leave AutoHandleHEAD disabled +and register explicit HEAD handlers only for routes that are safe to +expose (e.g. e.HEAD("/public", handler)). +You can leverage Echo.OnAddRoute callback to add HEAD routes explicitly from a single place.
+Disabled by default.
Routes is collection of RouteInfo instances with various helper methods.
type Routes []RouteInfoClone creates copy of Routes
FilterByMethod searched for matching route info by method
FilterByName searched for matching route info by name
FilterByPath searched for matching route info by path
FindByMethodPath searched for matching route info by method and path
Reverse reverses route to URL string by replacing path parameters with given params values.
StartConfig is for creating configured http.Server instance to start serve http(s) requests with given Echo instance
type StartConfig struct {
+ // Address specifies the address where listener will start listening on to serve HTTP(s) requests
+ Address string
+
+ // HideBanner instructs Start* method not to print banner when starting the Server.
+ HideBanner bool
+ // HidePort instructs Start* method not to print port when starting the Server.
+ HidePort bool
+
+ // CertFilesystem is filesystem is used to read `certFile` and `keyFile` when StartTLS method is called.
+ CertFilesystem fs.FS
+
+ // TLSConfig is used to configure TLS. If Listener is set, TLSConfig is not used to create the listener.
+ TLSConfig *tls.Config
+
+ // Listener is used to start server with the custom listener.
+ Listener net.Listener
+ // ListenerNetwork is used configure on which Network listener will use.
+ // If Listener is set, ListenerNetwork is not used.
+ ListenerNetwork string
+ // ListenerAddrFunc will be called after listener is created and started to listen for connections. This is useful in
+ // testing situations when server is started on random port `address = ":0"` in that case you can get actual port where
+ // listener is listening on.
+ ListenerAddrFunc func(addr net.Addr)
+
+ // GracefulTimeout is timeout value (defaults to 10sec) graceful shutdown will wait for server to handle ongoing requests
+ // before shutting down the server.
+ GracefulTimeout time.Duration
+ // OnShutdownError is called when graceful shutdown results an error. for example when listeners are not shut down within
+ // given timeout
+ OnShutdownError func(err error)
+
+ // BeforeServeFunc is callback that is called just before server starts to serve HTTP request.
+ // Use this callback when you want to configure http.Server different timeouts/limits/etc
+ BeforeServeFunc func(s *http.Server) error
+}Address string Address specifies the address where listener will start listening on to serve HTTP(s) requests
HideBanner bool HideBanner instructs Start* method not to print banner when starting the Server.
HidePort bool HidePort instructs Start* method not to print port when starting the Server.
CertFilesystem fs.FS CertFilesystem is filesystem is used to read certFile and keyFile when StartTLS method is called.
TLSConfig *tls.Config TLSConfig is used to configure TLS. If Listener is set, TLSConfig is not used to create the listener.
Listener net.Listener Listener is used to start server with the custom listener.
ListenerNetwork string ListenerNetwork is used configure on which Network listener will use. +If Listener is set, ListenerNetwork is not used.
ListenerAddrFunc func(addr net.Addr) ListenerAddrFunc will be called after listener is created and started to listen for connections. This is useful in
+testing situations when server is started on random port address = ":0" in that case you can get actual port where
+listener is listening on.
GracefulTimeout time.Duration GracefulTimeout is timeout value (defaults to 10sec) graceful shutdown will wait for server to handle ongoing requests +before shutting down the server.
OnShutdownError func(err error) OnShutdownError is called when graceful shutdown results an error. for example when listeners are not shut down within +given timeout
BeforeServeFunc func(s *http.Server) error BeforeServeFunc is callback that is called just before server starts to serve HTTP request. +Use this callback when you want to configure http.Server different timeouts/limits/etc
Start starts given Handler with HTTP(s) server.
StartTLS starts given Handler with HTTPS server.
+If certFile or keyFile is string the values are treated as file paths.
+If certFile or keyFile is []byte the values are treated as the certificate or key as-is.
TemplateRenderer is helper to ease creating renderers for html/template and text/template packages.
+Example usage:
e.Renderer = &echo.TemplateRenderer{
+ Template: template.Must(template.ParseGlob("templates/*.html")),
+ }
+
+ e.Renderer = &echo.TemplateRenderer{
+ Template: template.Must(template.New("hello").Parse("Hello, {{.}}!")),
+ }type TemplateRenderer struct {
+ Template interface {
+ ExecuteTemplate(wr io.Writer, name string, data any) error
+ }
+}Template interface {
+ ExecuteTemplate(wr io.Writer, name string, data any) error
+} Render renders the template with given data.
TimeLayout specifies the format for parsing time values in request parameters. +It can be a standard Go time layout string or one of the special Unix time layouts.
type TimeLayout stringTimeOpts is options for parsing time.Time values
type TimeOpts struct {
+ // Layout specifies the format for parsing time values in request parameters.
+ // It can be a standard Go time layout string or one of the special Unix time layouts.
+ //
+ // Parsing layout defaults to: echo.TimeLayout(time.RFC3339Nano)
+ // - To convert to custom layout use `echo.TimeLayout("2006-01-02")`
+ // - To convert unix timestamp (integer) to time.Time use `echo.TimeLayoutUnixTime`
+ // - To convert unix timestamp in milliseconds to time.Time use `echo.TimeLayoutUnixTimeMilli`
+ // - To convert unix timestamp in nanoseconds to time.Time use `echo.TimeLayoutUnixTimeNano`
+ Layout TimeLayout
+
+ // ParseInLocation is location used with time.ParseInLocation for layout that do not contain
+ // timezone information to set output time in given location.
+ // Defaults to time.UTC
+ ParseInLocation *time.Location
+
+ // ToInLocation is location to which parsed time is converted to after parsing.
+ // The parsed time will be converted using time.In(ToInLocation).
+ // Defaults to time.UTC
+ ToInLocation *time.Location
+}Layout TimeLayout Layout specifies the format for parsing time values in request parameters. +It can be a standard Go time layout string or one of the special Unix time layouts.
+Parsing layout defaults to: echo.TimeLayout(time.RFC3339Nano)
+echo.TimeLayout("2006-01-02")echo.TimeLayoutUnixTimeecho.TimeLayoutUnixTimeMilliecho.TimeLayoutUnixTimeNanoParseInLocation *time.Location ParseInLocation is location used with time.ParseInLocation for layout that do not contain +timezone information to set output time in given location. +Defaults to time.UTC
ToInLocation *time.Location ToInLocation is location to which parsed time is converted to after parsing. +The parsed time will be converted using time.In(ToInLocation). +Defaults to time.UTC
TrustOption is config for which IP address to trust
type TrustOption func(*ipChecker)Validator is the interface that wraps the Validate function.
type Validator interface {
+ Validate(i any) error
+}Validate func(i any) error ValueBinder provides utility methods for binding query or path parameter to various Go built-in types
type ValueBinder struct {
+ // ValueFunc is used to get single parameter (first) value from request
+ ValueFunc func(sourceParam string) string
+ // ValuesFunc is used to get all values for parameter from request. i.e. `/api/search?ids=1&ids=2`
+ ValuesFunc func(sourceParam string) []string
+ // ErrorFunc is used to create errors. Allows you to use your own error type, that for example marshals to your specific json response
+ ErrorFunc func(sourceParam string, values []string, message string, internalError error) error
+ // contains filtered or unexported fields
+}ValueFunc func(sourceParam string) string ValueFunc is used to get single parameter (first) value from request
ValuesFunc func(sourceParam string) []string ValuesFunc is used to get all values for parameter from request. i.e. /api/search?ids=1&ids=2
ErrorFunc func(sourceParam string, values []string, message string, internalError error) error ErrorFunc is used to create errors. Allows you to use your own error type, that for example marshals to your specific json response
BindError returns first seen bind error and resets/empties binder errors for further calls
{
+
+ failFastRouteFunc := func(c *echo.Context) error {
+ var opts struct {
+ IDs []int64
+ Active bool
+ }
+ length := int64(50)
+
+ b := echo.QueryParamsBinder(c)
+
+ err := b.Int64("length", &length).
+ Int64s("ids", &opts.IDs).
+ Bool("active", &opts.Active).
+ BindError()
+ if err != nil {
+ bErr := err.(*echo.BindingError)
+ return fmt.Errorf("my own custom error for field: %s values: %v", bErr.Field, bErr.Values)
+ }
+ fmt.Printf("active = %v, length = %v, ids = %v\n", opts.Active, length, opts.IDs)
+
+ return c.JSON(http.StatusOK, opts)
+ }
+
+ e := echo.New()
+ c := e.NewContext(
+ httptest.NewRequest(http.MethodGet, "/api/endpoint?active=true&length=25&ids=1&ids=2&ids=3", nil),
+ httptest.NewRecorder(),
+ )
+
+ _ = failFastRouteFunc(c)
+
+}Output:
+active = true, length = 25, ids = [1 2 3]BindErrors returns all bind errors and resets/empties binder errors for further calls
{
+
+ routeFunc := func(c *echo.Context) error {
+ var opts struct {
+ IDs []int64
+ Active bool
+ }
+ length := int64(50)
+
+ b := echo.QueryParamsBinder(c)
+
+ errs := b.Int64("length", &length).
+ Int64s("ids", &opts.IDs).
+ Bool("active", &opts.Active).
+ BindErrors()
+ if errs != nil {
+ for _, err := range errs {
+ bErr := err.(*echo.BindingError)
+ log.Printf("in case you want to access what field: %s values: %v failed", bErr.Field, bErr.Values)
+ }
+ return fmt.Errorf("%v fields failed to bind", len(errs))
+ }
+ fmt.Printf("active = %v, length = %v, ids = %v", opts.Active, length, opts.IDs)
+
+ return c.JSON(http.StatusOK, opts)
+ }
+
+ e := echo.New()
+ c := e.NewContext(
+ httptest.NewRequest(http.MethodGet, "/api/endpoint?active=true&length=25&ids=1&ids=2&ids=3", nil),
+ httptest.NewRecorder(),
+ )
+
+ _ = routeFunc(c)
+
+}Output:
+active = true, length = 25, ids = [1 2 3]BindUnmarshaler binds parameter to destination implementing BindUnmarshaler interface
BindWithDelimiter binds parameter to destination by suitable conversion function. +Delimiter is used before conversion to split parameter value to separate values
Bool binds parameter to bool variable
Bools binds parameter values to slice of bool variables
Byte binds parameter to byte variable
CustomFunc binds parameter values with Func. Func is called only when parameter values exist.
{
+
+ routeFunc := func(c *echo.Context) error {
+ length := int64(50)
+ var binary []byte
+
+ b := echo.QueryParamsBinder(c)
+ errs := b.Int64("length", &length).
+ CustomFunc("base64", func(values []string) []error {
+ if len(values) == 0 {
+ return nil
+ }
+ decoded, err := base64.URLEncoding.DecodeString(values[0])
+ if err != nil {
+
+ return []error{echo.NewBindingError("base64", values[0:1], "failed to decode base64", err)}
+ }
+ binary = decoded
+ return nil
+ }).
+ BindErrors()
+
+ if errs != nil {
+ for _, err := range errs {
+ bErr := err.(*echo.BindingError)
+ log.Printf("in case you want to access what field: %s values: %v failed", bErr.Field, bErr.Values)
+ }
+ return fmt.Errorf("%v fields failed to bind", len(errs))
+ }
+ fmt.Printf("length = %v, base64 = %s", length, binary)
+
+ return c.JSON(http.StatusOK, "ok")
+ }
+
+ e := echo.New()
+ c := e.NewContext(
+ httptest.NewRequest(http.MethodGet, "/api/endpoint?length=25&base64=SGVsbG8gV29ybGQ%3D", nil),
+ httptest.NewRecorder(),
+ )
+ _ = routeFunc(c)
+
+}Output:
+length = 25, base64 = Hello WorldDuration binds parameter to time.Duration variable
Durations binds parameter values to slice of time.Duration variables
FailFast set internal flag to indicate if binding methods will return early (without binding) when previous bind failed +NB: call this method before any other binding methods as it modifies binding methods behaviour
Float32 binds parameter to float32 variable
Float32s binds parameter values to slice of float32 variables
Float64 binds parameter to float64 variable
Float64s binds parameter values to slice of float64 variables
Int binds parameter to int variable
Int16 binds parameter to int16 variable
Int16s binds parameter to slice of int16
Int32 binds parameter to int32 variable
Int32s binds parameter to slice of int32
Int64 binds parameter to int64 variable
Int64s binds parameter to slice of int64
Int8 binds parameter to int8 variable
Int8s binds parameter to slice of int8
Ints binds parameter to slice of int
JSONUnmarshaler binds parameter to destination implementing json.Unmarshaler interface
MustBindUnmarshaler requires parameter value to exist to bind to destination implementing BindUnmarshaler interface. +Returns error when value does not exist
MustBindWithDelimiter requires parameter value to exist to bind destination by suitable conversion function. +Delimiter is used before conversion to split parameter value to separate values
MustBool requires parameter value to exist to bind to bool variable. Returns error when value does not exist
MustBools requires parameter values to exist to bind to slice of bool variables. Returns error when values does not exist
MustByte requires parameter value to exist to bind to byte variable. Returns error when value does not exist
MustCustomFunc requires parameter values to exist to bind with Func. Returns error when value does not exist.
MustDuration requires parameter value to exist to bind to time.Duration variable. Returns error when value does not exist
MustDurations requires parameter values to exist to bind to slice of time.Duration variables. Returns error when values does not exist
MustFloat32 requires parameter value to exist to bind to float32 variable. Returns error when value does not exist
MustFloat32s requires parameter values to exist to bind to slice of float32 variables. Returns error when values does not exist
MustFloat64 requires parameter value to exist to bind to float64 variable. Returns error when value does not exist
MustFloat64s requires parameter values to exist to bind to slice of float64 variables. Returns error when values does not exist
MustInt requires parameter value to exist to bind to int variable. Returns error when value does not exist
MustInt16 requires parameter value to exist to bind to int16 variable. Returns error when value does not exist
MustInt16s requires parameter value to exist to bind to int16 slice variable. Returns error when value does not exist
MustInt32 requires parameter value to exist to bind to int32 variable. Returns error when value does not exist
MustInt32s requires parameter value to exist to bind to int32 slice variable. Returns error when value does not exist
MustInt64 requires parameter value to exist to bind to int64 variable. Returns error when value does not exist
MustInt64s requires parameter value to exist to bind to int64 slice variable. Returns error when value does not exist
MustInt8 requires parameter value to exist to bind to int8 variable. Returns error when value does not exist
MustInt8s requires parameter value to exist to bind to int8 slice variable. Returns error when value does not exist
MustInts requires parameter value to exist to bind to int slice variable. Returns error when value does not exist
MustJSONUnmarshaler requires parameter value to exist to bind to destination implementing json.Unmarshaler interface. +Returns error when value does not exist
MustString requires parameter value to exist to bind to string variable. Returns error when value does not exist
MustStrings requires parameter values to exist to bind to slice of string variables. Returns error when value does not exist
MustTextUnmarshaler requires parameter value to exist to bind to destination implementing encoding.TextUnmarshaler interface. +Returns error when value does not exist
MustTime requires parameter value to exist to bind to time.Time variable. Returns error when value does not exist
MustTimes requires parameter values to exist to bind to slice of time.Time variables. Returns error when values does not exist
MustUint requires parameter value to exist to bind to uint variable. Returns error when value does not exist
MustUint16 requires parameter value to exist to bind to uint16 variable. Returns error when value does not exist
MustUint16s requires parameter value to exist to bind to uint16 slice variable. Returns error when value does not exist
MustUint32 requires parameter value to exist to bind to uint32 variable. Returns error when value does not exist
MustUint32s requires parameter value to exist to bind to uint32 slice variable. Returns error when value does not exist
MustUint64 requires parameter value to exist to bind to uint64 variable. Returns error when value does not exist
MustUint64s requires parameter value to exist to bind to uint64 slice variable. Returns error when value does not exist
MustUint8 requires parameter value to exist to bind to uint8 variable. Returns error when value does not exist
MustUint8s requires parameter value to exist to bind to uint8 slice variable. Returns error when value does not exist
MustUints requires parameter value to exist to bind to uint slice variable. Returns error when value does not exist
MustUnixTime requires parameter value to exist to bind to time.Time variable (in local time corresponding +to the given Unix time). Returns error when value does not exist.
+Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00
+Note:
+MustUnixTimeMilli requires parameter value to exist to bind to time.Time variable (in local time corresponding +to the given Unix time in millisecond precision). Returns error when value does not exist.
+Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00
+Note:
+MustUnixTimeNano requires parameter value to exist to bind to time.Time variable (in local time corresponding +to the given Unix time value in nanosecond precision). Returns error when value does not exist.
+Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 +Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 +Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00
+Note:
+String binds parameter to string variable
Strings binds parameter values to slice of string
TextUnmarshaler binds parameter to destination implementing encoding.TextUnmarshaler interface
Time binds parameter to time.Time variable
Times binds parameter values to slice of time.Time variables
Uint binds parameter to uint variable
Uint16 binds parameter to uint16 variable
Uint16s binds parameter to slice of uint16
Uint32 binds parameter to uint32 variable
Uint32s binds parameter to slice of uint32
Uint64 binds parameter to uint64 variable
Uint64s binds parameter to slice of uint64
Uint8 binds parameter to uint8 variable
Uint8s binds parameter to slice of uint8
Uints binds parameter to slice of uint
UnixTime binds parameter to time.Time variable (in local Time corresponding to the given Unix time).
+Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00
+Note:
+UnixTimeMilli binds parameter to time.Time variable (in local time corresponding to the given Unix time in millisecond precision).
+Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00
+Note:
+UnixTimeNano binds parameter to time.Time variable (in local time corresponding to the given Unix time in nanosecond precision).
+Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 +Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 +Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00
+Note:
+import "github.com/labstack/echo/v5/echotest"
LoadBytes is helper to load file contents relative to current (where test file is) package +directory.
TrimNewlineEnd instructs LoadBytes to remove \n from the end of loaded file.
Source: echotest/context.go:20
+ContextConfig is configuration for creating echo.Context for testing purposes.
type ContextConfig struct {
+ // Request will be used instead of default `httptest.NewRequest(http.MethodGet, "/", nil)`
+ Request *http.Request
+
+ // Response will be used instead of default `httptest.NewRecorder()`
+ Response *httptest.ResponseRecorder
+
+ // QueryValues will be set as Request.URL.RawQuery value
+ QueryValues url.Values
+
+ // Headers will be set as Request.Header value
+ Headers http.Header
+
+ // PathValues initializes context.PathValues with given value.
+ PathValues echo.PathValues
+
+ // RouteInfo initializes context.RouteInfo() with given value
+ RouteInfo *echo.RouteInfo
+
+ // FormValues creates form-urlencoded form out of given values. If there is no
+ // `content-type` header it will be set to `application/x-www-form-urlencoded`
+ // In case Request was not set the Request.Method is set to `POST`
+ //
+ // FormValues, MultipartForm and JSONBody are mutually exclusive.
+ FormValues url.Values
+
+ // MultipartForm creates multipart form out of given value. If there is no
+ // `content-type` header it will be set to `multipart/form-data`
+ // In case Request was not set the Request.Method is set to `POST`
+ //
+ // FormValues, MultipartForm and JSONBody are mutually exclusive.
+ MultipartForm *MultipartForm
+
+ // JSONBody creates JSON body out of given bytes. If there is no
+ // `content-type` header it will be set to `application/json`
+ // In case Request was not set the Request.Method is set to `POST`
+ //
+ // FormValues, MultipartForm and JSONBody are mutually exclusive.
+ JSONBody []byte
+}Request *http.Request Request will be used instead of default httptest.NewRequest(http.MethodGet, "/", nil)
Response *httptest.ResponseRecorder Response will be used instead of default httptest.NewRecorder()
QueryValues url.Values QueryValues will be set as Request.URL.RawQuery value
Headers http.Header Headers will be set as Request.Header value
PathValues echo.PathValues PathValues initializes context.PathValues with given value.
RouteInfo *echo.RouteInfo RouteInfo initializes context.RouteInfo() with given value
FormValues url.Values FormValues creates form-urlencoded form out of given values. If there is no
+content-type header it will be set to application/x-www-form-urlencoded
+In case Request was not set the Request.Method is set to POST
FormValues, MultipartForm and JSONBody are mutually exclusive.
MultipartForm *MultipartForm MultipartForm creates multipart form out of given value. If there is no
+content-type header it will be set to multipart/form-data
+In case Request was not set the Request.Method is set to POST
FormValues, MultipartForm and JSONBody are mutually exclusive.
JSONBody []byte JSONBody creates JSON body out of given bytes. If there is no
+content-type header it will be set to application/json
+In case Request was not set the Request.Method is set to POST
FormValues, MultipartForm and JSONBody are mutually exclusive.
Source: echotest/context.go:167
+ServeWithHandler serves ContextConfig with given handler and returns httptest.ResponseRecorder for response checking
Source: echotest/context.go:75
+ToContext converts ContextConfig to echo.Context
Source: echotest/context.go:81
+ToContextRecorder converts ContextConfig to echo.Context and httptest.ResponseRecorder
Source: echotest/context.go:62
+MultipartForm is used to create multipart form out of given value
type MultipartForm struct {
+ Fields map[string]string
+ Files []MultipartFormFile
+}Fields map[string]string Files []MultipartFormFile Source: echotest/context.go:68
+MultipartFormFile is used to create file in multipart form out of given value
type MultipartFormFile struct {
+ Fieldname string
+ Filename string
+ Content []byte
+}Fieldname string Filename string Content []byte import "github.com/labstack/echo/v5/middleware"
Rate limit response headers set by stores that implement RateLimiterStoreContext.
Source: middleware/rate_limiter.go:20
const (
+ HeaderXRateLimitLimit = "X-RateLimit-Limit"
+ HeaderXRateLimitRemaining = "X-RateLimit-Remaining"
+)const (
+
+ // KB is 1 KiloByte = 1024 bytes
+ KB
+ // MB is 1 Megabyte = 1_048_576 bytes
+ MB
+ // GB is 1 Gigabyte = 1_073_741_824 bytes
+ GB
+ // TB is 1 Terabyte = 1_099_511_627_776 bytes
+ TB
+ // PB is 1 Petabyte = 1_125_899_906_842_624 bytes
+ PB
+ // EB is 1 Exabyte = 1_152_921_504_606_847_000 bytes
+ EB
+)CSRFUsingSecFetchSite is a context key for CSRF middleware what is set when the client browser is using Sec-Fetch-Site +header and the request is deemed safe. +It is a dummy token value that can be used to render CSRF token for form by handlers.
+We know that the client is using a browser that supports Sec-Fetch-Site header, so when the form is submitted in +the future with this dummy token value it is OK. Although the request is safe, the template rendered by the +handler may need this value to render CSRF token for form.
const CSRFUsingSecFetchSite = "_echo_csrf_using_sec_fetch_site_"GZIPEncoding content-encoding header if set to "gzip", decompress body contents.
Source: middleware/decompress.go:32
const GZIPEncoding string = "gzip"StatusCodeContextCanceled is a custom HTTP status code for situations +where a client unexpectedly closed the connection to the server. +As there is no standard error code for "client closed connection", but +various well-known HTTP clients and server implement this HTTP code we use +499 too instead of the more problematic 5xx, which does not allow to detect this situation
Source: middleware/proxy.go:420
const StatusCodeContextCanceled = 499Source: middleware/extractor.go:25
const (
+ // ExtractorSourceHeader means value was extracted from request header
+ ExtractorSourceHeader ExtractorSource = "header"
+ // ExtractorSourceQuery means value was extracted from request query parameters
+ ExtractorSourceQuery ExtractorSource = "query"
+ // ExtractorSourcePathParam means value was extracted from route path parameters
+ ExtractorSourcePathParam ExtractorSource = "param"
+ // ExtractorSourceCookie means value was extracted from request cookies
+ ExtractorSourceCookie ExtractorSource = "cookie"
+ // ExtractorSourceForm means value was extracted from request form values
+ ExtractorSourceForm ExtractorSource = "form"
+)DefaultCSRFConfig is the default CSRF middleware config.
Source: middleware/csrf.go:104
var DefaultCSRFConfig = CSRFConfig{
+ Skipper: DefaultSkipper,
+ TokenLength: 32,
+ TokenLookup: "header:" + echo.HeaderXCSRFToken,
+ ContextKey: "csrf",
+ CookieName: "_csrf",
+ CookieMaxAge: 86400,
+ CookieSameSite: http.SameSiteDefaultMode,
+}DefaultKeyAuthConfig is the default KeyAuth middleware config.
Source: middleware/key_auth.go:112
var DefaultKeyAuthConfig = KeyAuthConfig{
+ Skipper: DefaultSkipper,
+ KeyLookup: "header:" + echo.HeaderAuthorization + ":Bearer ",
+}DefaultMethodOverrideConfig is the default MethodOverride middleware config.
Source: middleware/method_override.go:26
var DefaultMethodOverrideConfig = MethodOverrideConfig{
+ Skipper: DefaultSkipper,
+ Getter: MethodFromHeader(echo.HeaderXHTTPMethodOverride),
+}DefaultProxyConfig is the default Proxy middleware config.
Source: middleware/proxy.go:125
var DefaultProxyConfig = ProxyConfig{
+ Skipper: DefaultSkipper,
+ ContextKey: "target",
+}DefaultRateLimiterConfig defines default values for RateLimiterConfig
Source: middleware/rate_limiter.go:61
var DefaultRateLimiterConfig = RateLimiterConfig{
+ Skipper: DefaultSkipper,
+ IdentifierExtractor: func(ctx *echo.Context) (string, error) {
+ id := ctx.RealIP()
+ return id, nil
+ },
+ ErrorHandler: func(c *echo.Context, err error) error {
+ return ErrExtractorError.Wrap(err)
+ },
+ DenyHandler: func(c *echo.Context, identifier string, err error) error {
+ return ErrRateLimitExceeded.Wrap(err)
+ },
+}DefaultRateLimiterMemoryStoreConfig provides default configuration values for RateLimiterMemoryStore
Source: middleware/rate_limiter.go:251
var DefaultRateLimiterMemoryStoreConfig = RateLimiterMemoryStoreConfig{
+ ExpiresIn: 3 * time.Minute,
+}DefaultRecoverConfig is the default Recover middleware config.
Source: middleware/recover.go:34
var DefaultRecoverConfig = RecoverConfig{
+ Skipper: DefaultSkipper,
+ StackSize: 4 << 10,
+ DisableStackAll: false,
+ DisablePrintStack: false,
+}DefaultSecureConfig is the default Secure middleware config.
Source: middleware/secure.go:79
var DefaultSecureConfig = SecureConfig{
+ Skipper: DefaultSkipper,
+ XSSProtection: "1; mode=block",
+ ContentTypeNosniff: "nosniff",
+ XFrameOptions: "SAMEORIGIN",
+ HSTSPreloadEnabled: false,
+}DefaultStaticConfig is the default Static middleware config.
Source: middleware/static.go:159
var DefaultStaticConfig = StaticConfig{
+ Skipper: DefaultSkipper,
+ Index: "index.html",
+}ErrCSRFInvalid is returned when CSRF check fails
Source: middleware/csrf.go:101
var ErrCSRFInvalid = &echo.HTTPError{Code: http.StatusForbidden, Message: "invalid csrf token"}ErrExtractorError denotes an error raised when extractor function is unsuccessful
Source: middleware/rate_limiter.go:58
var ErrExtractorError = echo.NewHTTPError(http.StatusForbidden, "error while extracting identifier")ErrInvalidKey denotes an error raised when key value is invalid by validator
Source: middleware/key_auth.go:109
var ErrInvalidKey = echo.NewHTTPError(http.StatusUnauthorized, "invalid key")ErrKeyMissing denotes an error raised when key value could not be extracted from request
Source: middleware/key_auth.go:106
var ErrKeyMissing = echo.NewHTTPError(http.StatusUnauthorized, "missing key")ErrRateLimitExceeded denotes an error raised when rate limit is exceeded
Source: middleware/rate_limiter.go:55
var ErrRateLimitExceeded = echo.NewHTTPError(http.StatusTooManyRequests, "rate limit exceeded")RedirectHTTPSConfig is the HTTPS Redirect middleware config.
Source: middleware/redirect.go:34
var RedirectHTTPSConfig = RedirectConfig{/* contains filtered or unexported fields */}RedirectHTTPSWWWConfig is the HTTPS WWW Redirect middleware config.
Source: middleware/redirect.go:37
var RedirectHTTPSWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}RedirectNonHTTPSWWWConfig is the non HTTPS WWW Redirect middleware config.
Source: middleware/redirect.go:40
var RedirectNonHTTPSWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}RedirectNonWWWConfig is the non WWW Redirect middleware config.
Source: middleware/redirect.go:46
var RedirectNonWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}RedirectWWWConfig is the WWW Redirect middleware config.
Source: middleware/redirect.go:43
var RedirectWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}Source: middleware/slash.go:29
+AddTrailingSlash returns a root level (before router) middleware which adds a
+trailing slash to the request URL#Path.
Usage Echo#Pre(AddTrailingSlash())
Source: middleware/slash.go:34
+AddTrailingSlashWithConfig returns an AddTrailingSlash middleware with config or panics on invalid configuration.
Source: middleware/basic_auth.go:87
+BasicAuth returns an BasicAuth middleware.
+For valid credentials it calls the next handler. +For missing or invalid credentials, it sends "401 - Unauthorized" response.
Source: middleware/basic_auth.go:92
+BasicAuthWithConfig returns an BasicAuthWithConfig middleware with config.
Source: middleware/body_dump.go:58
+BodyDump returns a BodyDump middleware.
+BodyDump middleware captures the request and response payload and calls the +registered handler.
+SECURITY: By default, this limits dumped bodies to 5MB to prevent memory exhaustion +attacks. To customize limits, use BodyDumpWithConfig. To disable limits (not recommended +in production), explicitly set MaxRequestBytes and MaxResponseBytes to -1.
Source: middleware/body_dump.go:68
+BodyDumpWithConfig returns a BodyDump middleware with config.
+See: BodyDump().
SECURITY: If MaxRequestBytes and MaxResponseBytes are not set (zero values), they default +to 5MB each to prevent DoS attacks via large payloads. Set them explicitly to -1 to disable +limits if needed for your use case.
Source: middleware/body_limit.go:34
+BodyLimit returns a BodyLimit middleware.
+BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it
+sends "413 - Request Entity Too Large" response. The BodyLimit is determined based on both Content-Length request
+header and actual content read, which makes it super secure.
Source: middleware/body_limit.go:42
+BodyLimitWithConfig returns a BodyLimitWithConfig middleware. Middleware sets the maximum allowed size in bytes for
+a request body, if the size exceeds the configured limit, it sends "413 - Request Entity Too Large" response.
+The BodyLimitWithConfig is determined based on both Content-Length request header and actual content read, which
+makes it super secure.
Source: middleware/cors.go:137
+CORS returns a Cross-Origin Resource Sharing (CORS) middleware. +See also MDN: Cross-Origin Resource Sharing (CORS).
+Origin consist of following parts: scheme + "://" + host + optional ":" + port
+Wildcard * can be used, but has to be set explicitly.
+Example: https://example.com, http://example.com:8080, *
Security: Poorly configured CORS can compromise security because it allows +relaxation of the browser's Same-Origin policy. See Exploiting CORS +misconfigurations for Bitcoins and bounties and Portswigger: Cross-origin +resource sharing (CORS) for more details.
+Duplicate CORS headers can appear in a chained-proxy setup where this +middleware runs on more than one layer and a reverse proxy copies an +upstream's CORS headers on top of the ones set here. Prefer enabling CORS +only at the edge; if a proxied upstream sets its own CORS headers, strip them +before they are copied (e.g. httputil.ReverseProxy.ModifyResponse).
Source: middleware/cors.go:146
+CORSWithConfig returns a CORS middleware with config or panics on invalid configuration. +See: [CORS].
Source: middleware/csrf.go:116
+CSRF returns a Cross-Site Request Forgery (CSRF) middleware. +See: https://en.wikipedia.org/wiki/Cross-site_request_forgery
Source: middleware/csrf.go:121
+CSRFWithConfig returns a CSRF middleware with config or panics on invalid configuration.
Source: middleware/context_timeout.go:28
+ContextTimeout returns a middleware which returns error (503 Service Unavailable error) to client +when underlying method returns context.DeadlineExceeded error.
Source: middleware/context_timeout.go:33
+ContextTimeoutWithConfig returns a Timeout middleware with config.
Source: middleware/extractor.go:74
+CreateExtractors creates ValuesExtractors from given lookups.
+lookups is a string in the form of "
<cut-prefix> is argument value to cut/trim prefix of the extracted value. This is useful if header
+value has static prefix like Authorization: <auth-scheme> <authorisation-parameters> where part that we
+want to cut is <auth-scheme> note the space at the end.
+In case of basic authentication Authorization: Basic <credentials> prefix we want to remove is Basic .Multiple sources example:
+limit sets the maximum amount how many lookups can be returned.
Source: middleware/decompress.go:52
+Decompress decompresses request body based if content encoding type is set to "gzip" with default config
+SECURITY: By default, this limits decompressed data to 100MB to prevent zip bomb attacks. +To customize the limit, use DecompressWithConfig. To disable limits (not recommended in production), +set MaxDecompressedSize to -1.
Source: middleware/decompress.go:60
+DecompressWithConfig returns a decompress middleware with config or panics on invalid configuration.
+SECURITY: If MaxDecompressedSize is not set (zero value), it defaults to 100MB to prevent +DoS attacks via zip bombs. Set to -1 to explicitly disable limits if needed for your use case.
Source: middleware/middleware.go:87
+DefaultSkipper returns false which processes the middleware.
Source: middleware/compress.go:59
+Gzip returns a middleware which compresses HTTP response using gzip compression scheme.
Source: middleware/compress.go:64
+GzipWithConfig returns a middleware which compresses HTTP response using gzip compression scheme.
Source: middleware/redirect.go:80
+HTTPSNonWWWRedirect redirects http requests to https non www. +For example, http://www.labstack.com will be redirect to https://labstack.com.
+Usage Echo#Pre(HTTPSNonWWWRedirect())
Source: middleware/redirect.go:85
+HTTPSNonWWWRedirectWithConfig returns a HTTPS Non-WWW redirect middleware with config or panics on invalid configuration.
Source: middleware/redirect.go:52
+HTTPSRedirect redirects http requests to https. +For example, http://labstack.com will be redirect to https://labstack.com.
+Usage Echo#Pre(HTTPSRedirect())
Source: middleware/redirect.go:57
+HTTPSRedirectWithConfig returns a HTTPS redirect middleware with config or panics on invalid configuration.
Source: middleware/redirect.go:66
+HTTPSWWWRedirect redirects http requests to https www. +For example, http://labstack.com will be redirect to https://www.labstack.com.
+Usage Echo#Pre(HTTPSWWWRedirect())
Source: middleware/redirect.go:71
+HTTPSWWWRedirectWithConfig returns a HTTPS WWW redirect middleware with config or panics on invalid configuration.
Source: middleware/key_auth.go:122
+KeyAuth returns an KeyAuth middleware.
+For valid key it calls the next handler. +For invalid key, it sends "401 - Unauthorized" response. +For missing key, it sends "400 - Bad Request" response.
Source: middleware/key_auth.go:133
+KeyAuthWithConfig returns an KeyAuth middleware or panics if configuration is invalid.
+For first valid key it calls the next handler. +For invalid key, it sends "401 - Unauthorized" response. +For missing key, it sends "400 - Bad Request" response.
Source: middleware/method_override.go:83
+MethodFromForm is a MethodOverrideGetter that gets overridden method from the
+form parameter.
Source: middleware/method_override.go:75
+MethodFromHeader is a MethodOverrideGetter that gets overridden method from
+the request header.
Source: middleware/method_override.go:91
+MethodFromQuery is a MethodOverrideGetter that gets overridden method from
+the query parameter.
Source: middleware/method_override.go:36
+MethodOverride returns a MethodOverride middleware. +MethodOverride middleware checks for the overridden method from the request and +uses it instead of the original method.
+For security reasons, only POST method can be overridden.
Source: middleware/method_override.go:41
+MethodOverrideWithConfig returns a Method Override middleware with config or panics on invalid configuration.
Source: middleware/proxy.go:189
+NewRandomBalancer returns a random proxy balancer.
Source: middleware/rate_limiter.go:200
+NewRateLimiterMemoryStore returns an instance of RateLimiterMemoryStore with +the provided rate (as req/s). +for more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit.
+Burst and ExpiresIn will be set to default values.
+Note that if the provided rate is a float number and Burst is zero, Burst will be treated as the rounded up value of the rate.
+Example (with 20 requests/sec):
+limiterStore := middleware.NewRateLimiterMemoryStore(20)Source: middleware/rate_limiter.go:225
+NewRateLimiterMemoryStoreWithConfig returns an instance of RateLimiterMemoryStore +with the provided configuration. Rate must be provided. Burst will be set to the rounded up value of +the configured rate if not provided or set to 0.
+The built-in memory store is usually capable for modest loads. For higher loads other +store implementations should be considered.
+Characteristics:
+Example:
+limiterStore := middleware.NewRateLimiterMemoryStoreWithConfig(
+ middleware.RateLimiterMemoryStoreConfig{Rate: 50, Burst: 200, ExpiresIn: 5 * time.Minute},
+)Source: middleware/proxy.go:199
+NewRoundRobinBalancer returns a round-robin proxy balancer.
Source: middleware/redirect.go:108
+NonWWWRedirect redirects www requests to non www. +For example, http://www.labstack.com will be redirect to http://labstack.com.
+Usage Echo#Pre(NonWWWRedirect())
Source: middleware/redirect.go:113
+NonWWWRedirectWithConfig returns a Non-WWW redirect middleware with config or panics on invalid configuration.
Source: middleware/proxy.go:292
+Proxy returns a Proxy middleware.
+Proxy middleware forwards the request to upstream server using a configured load balancing technique.
Source: middleware/proxy.go:301
+ProxyWithConfig returns a Proxy middleware or panics if configuration is invalid.
+Proxy middleware forwards the request to upstream server using a configured load balancing technique.
Source: middleware/rate_limiter.go:86
+RateLimiter returns a rate limiting middleware
+e := echo.New()
+
+limiterStore := middleware.NewRateLimiterMemoryStore(20)
+
+e.GET("/rate-limited", func(c *echo.Context) error {
+ return c.String(http.StatusOK, "test")
+}, RateLimiter(limiterStore))Source: middleware/rate_limiter.go:119
+RateLimiterWithConfig returns a rate limiting middleware
+e := echo.New()
+
+config := middleware.RateLimiterConfig{
+ Skipper: DefaultSkipper,
+ Store: middleware.NewRateLimiterMemoryStore(
+ middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute}
+ )
+ IdentifierExtractor: func(ctx *echo.Context) (string, error) {
+ id := ctx.RealIP()
+ return id, nil
+ },
+ ErrorHandler: func(ctx *echo.Context, err error) error {
+ return context.JSON(http.StatusTooManyRequests, nil)
+ },
+ DenyHandler: func(ctx *echo.Context, identifier string, err error) error {
+ return context.JSON(http.StatusForbidden, nil)
+ },
+}
+
+e.GET("/rate-limited", func(c *echo.Context) error {
+ return c.String(http.StatusOK, "test")
+}, middleware.RateLimiterWithConfig(config))Source: middleware/recover.go:43
+Recover returns a middleware which recovers from panics anywhere in the chain +and handles the control to the centralized HTTPErrorHandler.
Source: middleware/recover.go:48
+RecoverWithConfig returns a Recovery middleware with config or panics on invalid configuration.
Source: middleware/slash.go:93
+RemoveTrailingSlash returns a root level (before router) middleware which removes +a trailing slash from the request URI.
+Usage Echo#Pre(RemoveTrailingSlash())
Source: middleware/slash.go:98
+RemoveTrailingSlashWithConfig returns a RemoveTrailingSlash middleware with config or panics on invalid configuration.
Source: middleware/request_id.go:30
+RequestID returns a middleware that reads RequestIDConfig.TargetHeader (X-Request-ID) header value or when
+the header value is empty, generates that value and sets request ID to response
+as RequestIDConfig.TargetHeader (X-Request-Id) value.
Source: middleware/request_id.go:37
+RequestIDWithConfig returns a middleware with given valid config or panics on invalid configuration.
+The middleware reads RequestIDConfig.TargetHeader (X-Request-ID) header value or when the header value is empty,
+generates that value and sets request ID to response as RequestIDConfig.TargetHeader (X-Request-Id) value.
Source: middleware/request_logger.go:395
+RequestLogger creates Request Logger middleware with Echo default settings that uses Context.Logger() as logger.
Source: middleware/request_logger.go:237
+RequestLoggerWithConfig returns a RequestLogger middleware with config.
Source: middleware/rewrite.go:40
+Rewrite returns a Rewrite middleware.
+Rewrite middleware rewrites the URL path based on the provided rules.
Source: middleware/rewrite.go:49
+RewriteWithConfig returns a Rewrite middleware or panics on invalid configuration.
+Rewrite middleware rewrites the URL path based on the provided rules.
Source: middleware/secure.go:91
+Secure returns a Secure middleware. +Secure middleware provides protection against cross-site scripting (XSS) attack, +content type sniffing, clickjacking, insecure connection and other code injection +attacks.
Source: middleware/secure.go:96
+SecureWithConfig returns a Secure middleware with config or panics on invalid configuration.
Source: middleware/static.go:165
+Static returns a Static middleware to serves static content from the provided root directory.
Source: middleware/static.go:172
+StaticWithConfig returns a Static middleware to serves static content or panics on invalid configuration.
Source: middleware/redirect.go:94
+WWWRedirect redirects non www requests to www. +For example, http://labstack.com will be redirect to http://www.labstack.com.
+Usage Echo#Pre(WWWRedirect())
Source: middleware/redirect.go:99
+WWWRedirectWithConfig returns a WWW redirect middleware with config or panics on invalid configuration.
Source: middleware/slash.go:15
+AddTrailingSlashConfig is the middleware config for adding trailing slash to the request.
type AddTrailingSlashConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Status code to be used when redirecting the request.
+ // Optional, but when provided the request is redirected using this code.
+ // Valid status codes: [300...308]
+ RedirectCode int
+}Skipper Skipper Skipper defines a function to skip middleware.
RedirectCode int Status code to be used when redirecting the request. +Optional, but when provided the request is redirected using this code. +Valid status codes: [300...308]
Source: middleware/slash.go:39
+ToMiddleware converts AddTrailingSlashConfig to middleware or returns an error for invalid configuration
Source: middleware/basic_auth.go:21
+BasicAuthConfig defines the config for BasicAuthWithConfig middleware.
+SECURITY: The Validator function is responsible for securely comparing credentials. +See BasicAuthValidator documentation for guidance on preventing timing attacks.
type BasicAuthConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Validator is a function to validate BasicAuthWithConfig credentials. Note: if request contains multiple basic auth headers
+ // this function would be called once for each header until first valid result is returned
+ // Required.
+ Validator BasicAuthValidator
+
+ // Realm is a string to define realm attribute of BasicAuthWithConfig.
+ // Default value "Restricted".
+ Realm string
+
+ // AllowedCheckLimit set how many headers are allowed to be checked. This is useful
+ // environments like corporate test environments with application proxies restricting
+ // access to environment with their own auth scheme.
+ // Defaults to 1.
+ AllowedCheckLimit uint
+}Skipper Skipper Skipper defines a function to skip middleware.
Validator BasicAuthValidator Validator is a function to validate BasicAuthWithConfig credentials. Note: if request contains multiple basic auth headers +this function would be called once for each header until first valid result is returned +Required.
Realm string Realm is a string to define realm attribute of BasicAuthWithConfig. +Default value "Restricted".
AllowedCheckLimit uint AllowedCheckLimit set how many headers are allowed to be checked. This is useful +environments like corporate test environments with application proxies restricting +access to environment with their own auth scheme. +Defaults to 1.
Source: middleware/basic_auth.go:97
+ToMiddleware converts BasicAuthConfig to middleware or returns an error for invalid configuration
Source: middleware/basic_auth.go:76
+BasicAuthValidator defines a function to validate BasicAuthWithConfig credentials.
+SECURITY WARNING: To prevent timing attacks that could allow attackers to enumerate +valid usernames or passwords, validator implementations MUST use constant-time +comparison for credential checking. Use crypto/subtle.ConstantTimeCompare instead +of standard string equality (==) or switch statements.
+Example of SECURE implementation:
+import "crypto/subtle"
+
+validator := func(c *echo.Context, username, password string) (bool, error) {
+ // Fetch expected credentials from database/config
+ expectedUser := "admin"
+ expectedPass := "secretpassword"
+
+ // Use constant-time comparison to prevent timing attacks
+ userMatch := subtle.ConstantTimeCompare([]byte(username), []byte(expectedUser)) == 1
+ passMatch := subtle.ConstantTimeCompare([]byte(password), []byte(expectedPass)) == 1
+
+ if userMatch && passMatch {
+ return true, nil
+ }
+ return false, nil
+}Example of INSECURE implementation (DO NOT USE):
+// VULNERABLE TO TIMING ATTACKS - DO NOT USE
+validator := func(c *echo.Context, username, password string) (bool, error) {
+ if username == "admin" && password == "secret" { // Timing leak!
+ return true, nil
+ }
+ return false, nil
+}type BasicAuthValidator func(c *echo.Context, user string, password string) (bool, error)Source: middleware/middleware.go:19
+BeforeFunc defines a function which is executed just before the middleware.
type BeforeFunc func(c *echo.Context)Source: middleware/body_dump.go:19
+BodyDumpConfig defines the config for BodyDump middleware.
type BodyDumpConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Handler receives request, response payloads and handler error if there are any.
+ // Required.
+ Handler BodyDumpHandler
+
+ // MaxRequestBytes limits how much of the request body to dump.
+ // If the request body exceeds this limit, only the first MaxRequestBytes
+ // are dumped. The handler callback receives truncated data.
+ // Default: 5 * MB (5,242,880 bytes)
+ // Set to -1 to disable limits (not recommended in production).
+ MaxRequestBytes int64
+
+ // MaxResponseBytes limits how much of the response body to dump.
+ // If the response body exceeds this limit, only the first MaxResponseBytes
+ // are dumped. The handler callback receives truncated data.
+ // Default: 5 * MB (5,242,880 bytes)
+ // Set to -1 to disable limits (not recommended in production).
+ MaxResponseBytes int64
+}Skipper Skipper Skipper defines a function to skip middleware.
Handler BodyDumpHandler Handler receives request, response payloads and handler error if there are any. +Required.
MaxRequestBytes int64 MaxRequestBytes limits how much of the request body to dump. +If the request body exceeds this limit, only the first MaxRequestBytes +are dumped. The handler callback receives truncated data. +Default: 5 * MB (5,242,880 bytes) +Set to -1 to disable limits (not recommended in production).
MaxResponseBytes int64 MaxResponseBytes limits how much of the response body to dump. +If the response body exceeds this limit, only the first MaxResponseBytes +are dumped. The handler callback receives truncated data. +Default: 5 * MB (5,242,880 bytes) +Set to -1 to disable limits (not recommended in production).
Source: middleware/body_dump.go:73
+ToMiddleware converts BodyDumpConfig to middleware or returns an error for invalid configuration
Source: middleware/body_dump.go:43
+BodyDumpHandler receives the request and response payload.
type BodyDumpHandler func(c *echo.Context, reqBody []byte, resBody []byte, err error)Source: middleware/body_limit.go:15
+BodyLimitConfig defines the config for BodyLimitWithConfig middleware.
type BodyLimitConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // LimitBytes is maximum allowed size in bytes for a request body
+ LimitBytes int64
+}Skipper Skipper Skipper defines a function to skip middleware.
LimitBytes int64 LimitBytes is maximum allowed size in bytes for a request body
Source: middleware/body_limit.go:47
+ToMiddleware converts BodyLimitConfig to middleware or returns an error for invalid configuration
CORSConfig defines the config for CORS middleware.
type CORSConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // AllowOrigins determines the value of the Access-Control-Allow-Origin
+ // response header. This header defines a list of origins that may access the
+ // resource.
+ //
+ // Origin consist of following parts: `scheme + "://" + host + optional ":" + port`
+ // Wildcard can be used, but has to be set explicitly []string{"*"}
+ // Example: `https://example.com`, `http://example.com:8080`, `*`
+ //
+ // Security: use extreme caution when handling the origin, and carefully
+ // validate any logic. Remember that attackers may register hostile domain names.
+ // See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
+ // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
+ //
+ // Mandatory.
+ AllowOrigins []string
+
+ // UnsafeAllowOriginFunc is an optional custom function to validate the origin. It takes the
+ // origin as an argument and returns
+ // - string, allowed origin
+ // - bool, true if allowed or false otherwise.
+ // - error, if an error is returned, it is returned immediately by the handler.
+ // If this option is set, AllowOrigins is ignored.
+ //
+ // Security: use extreme caution when handling the origin, and carefully
+ // validate any logic. Remember that attackers may register hostile (sub)domain names.
+ // See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
+ //
+ // Sub-domain checks example:
+ // UnsafeAllowOriginFunc: func(c *echo.Context, origin string) (string, bool, error) {
+ // if strings.HasSuffix(origin, ".example.com") {
+ // return origin, true, nil
+ // }
+ // return "", false, nil
+ // },
+ //
+ // Optional.
+ UnsafeAllowOriginFunc func(c *echo.Context, origin string) (allowedOrigin string, allowed bool, err error)
+
+ // AllowMethods determines the value of the Access-Control-Allow-Methods
+ // response header. This header specified the list of methods allowed when
+ // accessing the resource. This is used in response to a preflight request.
+ //
+ // Optional. Default value DefaultCORSConfig.AllowMethods.
+ // If `allowMethods` is left empty, this middleware will fill for preflight
+ // request `Access-Control-Allow-Methods` header value
+ // from `Allow` header that echo.Router set into context.
+ //
+ // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
+ AllowMethods []string
+
+ // AllowHeaders determines the value of the Access-Control-Allow-Headers
+ // response header. This header is used in response to a preflight request to
+ // indicate which HTTP headers can be used when making the actual request.
+ //
+ // Optional. Defaults to empty list. No domains allowed for CORS.
+ //
+ // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
+ AllowHeaders []string
+
+ // AllowCredentials determines the value of the
+ // Access-Control-Allow-Credentials response header. This header indicates
+ // whether or not the response to the request can be exposed when the
+ // credentials mode (Request.credentials) is true. When used as part of a
+ // response to a preflight request, this indicates whether or not the actual
+ // request can be made using credentials. See also
+ // [MDN: Access-Control-Allow-Credentials].
+ //
+ // Optional. Default value false, in which case the header is not set.
+ //
+ // Security: avoid using `AllowCredentials = true` with `AllowOrigins = *`.
+ // See "Exploiting CORS misconfigurations for Bitcoins and bounties",
+ // https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
+ //
+ // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
+ AllowCredentials bool
+
+ // ExposeHeaders determines the value of Access-Control-Expose-Headers, which
+ // defines a list of headers that clients are allowed to access.
+ //
+ // Optional. Default value []string{}, in which case the header is not set.
+ //
+ // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Header
+ ExposeHeaders []string
+
+ // MaxAge determines the value of the Access-Control-Max-Age response header.
+ // This header indicates how long (in seconds) the results of a preflight
+ // request can be cached.
+ // The header is set only if MaxAge != 0, negative value sends "0" which instructs browsers not to cache that response.
+ //
+ // Optional. Default value 0 - meaning header is not sent.
+ //
+ // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
+ MaxAge int
+}Skipper Skipper Skipper defines a function to skip middleware.
AllowOrigins []string AllowOrigins determines the value of the Access-Control-Allow-Origin +response header. This header defines a list of origins that may access the +resource.
+Origin consist of following parts: scheme + "://" + host + optional ":" + port
+Wildcard can be used, but has to be set explicitly []string{"*"}
+Example: https://example.com, http://example.com:8080, *
Security: use extreme caution when handling the origin, and carefully +validate any logic. Remember that attackers may register hostile domain names. +See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html +See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
+Mandatory.
UnsafeAllowOriginFunc func(c *echo.Context, origin string) (allowedOrigin string, allowed bool, err error) UnsafeAllowOriginFunc is an optional custom function to validate the origin. It takes the +origin as an argument and returns
+Security: use extreme caution when handling the origin, and carefully +validate any logic. Remember that attackers may register hostile (sub)domain names. +See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
+Sub-domain checks example: + UnsafeAllowOriginFunc: func(c *echo.Context, origin string) (string, bool, error) { + if strings.HasSuffix(origin, ".example.com") { + return origin, true, nil + } + return "", false, nil + },
+Optional.
AllowMethods []string AllowMethods determines the value of the Access-Control-Allow-Methods +response header. This header specified the list of methods allowed when +accessing the resource. This is used in response to a preflight request.
+Optional. Default value DefaultCORSConfig.AllowMethods.
+If allowMethods is left empty, this middleware will fill for preflight
+request Access-Control-Allow-Methods header value
+from Allow header that echo.Router set into context.
See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
AllowHeaders []string AllowHeaders determines the value of the Access-Control-Allow-Headers +response header. This header is used in response to a preflight request to +indicate which HTTP headers can be used when making the actual request.
+Optional. Defaults to empty list. No domains allowed for CORS.
+See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
AllowCredentials bool AllowCredentials determines the value of the +Access-Control-Allow-Credentials response header. This header indicates +whether or not the response to the request can be exposed when the +credentials mode (Request.credentials) is true. When used as part of a +response to a preflight request, this indicates whether or not the actual +request can be made using credentials. See also +[MDN: Access-Control-Allow-Credentials].
+Optional. Default value false, in which case the header is not set.
+Security: avoid using AllowCredentials = true with AllowOrigins = *.
+See "Exploiting CORS misconfigurations for Bitcoins and bounties",
+https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
ExposeHeaders []string ExposeHeaders determines the value of Access-Control-Expose-Headers, which +defines a list of headers that clients are allowed to access.
+Optional. Default value []string{}, in which case the header is not set.
+See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Header
MaxAge int MaxAge determines the value of the Access-Control-Max-Age response header. +This header indicates how long (in seconds) the results of a preflight +request can be cached. +The header is set only if MaxAge != 0, negative value sends "0" which instructs browsers not to cache that response.
+Optional. Default value 0 - meaning header is not sent.
+See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
Source: middleware/cors.go:151
+ToMiddleware converts CORSConfig to middleware or returns an error for invalid configuration
CSRFConfig defines the config for CSRF middleware.
type CSRFConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+ // TrustedOrigins permits any request with `Sec-Fetch-Site` header whose `Origin` header
+ // exactly matches a configured origin.
+ // Values should be formatted as Origin header "scheme://host[:port]".
+ //
+ // See [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
+ // See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headers
+ TrustedOrigins []string
+
+ // AllowSecFetchSiteFunc allows custom behaviour for `Sec-Fetch-Site` requests that are about to
+ // fail with CSRF error, to be allowed or replaced with custom error.
+ // This function applies to `Sec-Fetch-Site` values:
+ // - `same-site` same registrable domain (subdomain and/or different port)
+ // - `cross-site` request originates from different site
+ // See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headers
+ AllowSecFetchSiteFunc func(c *echo.Context) (bool, error)
+
+ // TokenLength is the length of the generated token.
+ TokenLength uint8
+
+ // TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
+ // to extract token from the request.
+ // Optional. Default value "header:X-CSRF-Token".
+ // Possible values:
+ // - "header:<name>" or "header:<name>:<cut-prefix>"
+ // - "query:<name>"
+ // - "form:<name>"
+ // Multiple sources example:
+ // - "header:X-CSRF-Token,query:csrf"
+ TokenLookup string `yaml:"token_lookup"`
+
+ // Generator defines a function to generate token.
+ // Optional. Defaults to randomString(TokenLength).
+ Generator func() string
+
+ // Context key to store generated CSRF token into context.
+ // Optional. Default value "csrf".
+ ContextKey string
+
+ // Name of the CSRF cookie. This cookie will store CSRF token.
+ // Optional. Default value "csrf".
+ CookieName string
+
+ // Domain of the CSRF cookie.
+ // Optional. Default value none.
+ CookieDomain string
+
+ // Path of the CSRF cookie.
+ // Optional. Default value none.
+ CookiePath string
+
+ // Max age (in seconds) of the CSRF cookie.
+ // Optional. Default value 86400 (24hr).
+ CookieMaxAge int
+
+ // Indicates if CSRF cookie is secure.
+ // Optional. Default value false.
+ CookieSecure bool
+
+ // Indicates if CSRF cookie is HTTP only.
+ // Optional. Default value false.
+ CookieHTTPOnly bool
+
+ // Indicates SameSite mode of the CSRF cookie.
+ // Optional. Default value SameSiteDefaultMode.
+ CookieSameSite http.SameSite
+
+ // ErrorHandler defines a function which is executed for returning custom errors.
+ ErrorHandler func(c *echo.Context, err error) error
+}Skipper Skipper Skipper defines a function to skip middleware.
TrustedOrigins []string TrustedOrigins permits any request with Sec-Fetch-Site header whose Origin header
+exactly matches a configured origin.
+Values should be formatted as Origin header "scheme://host[:port]".
See [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin +See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headers
AllowSecFetchSiteFunc func(c *echo.Context) (bool, error) AllowSecFetchSiteFunc allows custom behaviour for Sec-Fetch-Site requests that are about to
+fail with CSRF error, to be allowed or replaced with custom error.
+This function applies to Sec-Fetch-Site values:
same-site same registrable domain (subdomain and/or different port)cross-site request originates from different site
+See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headersTokenLength uint8 TokenLength is the length of the generated token.
TokenLookup string `yaml:"token_lookup"`TokenLookup is a string in the form of "
Generator func() string Generator defines a function to generate token. +Optional. Defaults to randomString(TokenLength).
ContextKey string Context key to store generated CSRF token into context. +Optional. Default value "csrf".
CookieName string Name of the CSRF cookie. This cookie will store CSRF token. +Optional. Default value "csrf".
CookieDomain string Domain of the CSRF cookie. +Optional. Default value none.
CookiePath string Path of the CSRF cookie. +Optional. Default value none.
CookieMaxAge int Max age (in seconds) of the CSRF cookie. +Optional. Default value 86400 (24hr).
CookieSecure bool Indicates if CSRF cookie is secure. +Optional. Default value false.
CookieHTTPOnly bool Indicates if CSRF cookie is HTTP only. +Optional. Default value false.
CookieSameSite http.SameSite Indicates SameSite mode of the CSRF cookie. +Optional. Default value SameSiteDefaultMode.
ErrorHandler func(c *echo.Context, err error) error ErrorHandler defines a function which is executed for returning custom errors.
Source: middleware/csrf.go:126
+ToMiddleware converts CSRFConfig to middleware or returns an error for invalid configuration
Source: middleware/context_timeout.go:15
+ContextTimeoutConfig defines the config for ContextTimeout middleware.
type ContextTimeoutConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // ErrorHandler is a function when error arises in middeware execution.
+ ErrorHandler func(c *echo.Context, err error) error
+
+ // Timeout configures a timeout for the middleware
+ Timeout time.Duration
+}Skipper Skipper Skipper defines a function to skip middleware.
ErrorHandler func(c *echo.Context, err error) error ErrorHandler is a function when error arises in middeware execution.
Timeout time.Duration Timeout configures a timeout for the middleware
Source: middleware/context_timeout.go:38
+ToMiddleware converts Config to middleware.
Source: middleware/decompress.go:16
+DecompressConfig defines the config for Decompress middleware.
type DecompressConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers
+ GzipDecompressPool Decompressor
+
+ // MaxDecompressedSize limits the maximum size of decompressed request body in bytes.
+ // If the decompressed body exceeds this limit, the middleware returns HTTP 413 error.
+ // This prevents zip bomb attacks where small compressed payloads decompress to huge sizes.
+ // Default: 100 * MB (104,857,600 bytes)
+ // Set to -1 to disable limits (not recommended in production).
+ MaxDecompressedSize int64
+}Skipper Skipper Skipper defines a function to skip middleware.
GzipDecompressPool Decompressor GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers
MaxDecompressedSize int64 MaxDecompressedSize limits the maximum size of decompressed request body in bytes. +If the decompressed body exceeds this limit, the middleware returns HTTP 413 error. +This prevents zip bomb attacks where small compressed payloads decompress to huge sizes. +Default: 100 * MB (104,857,600 bytes) +Set to -1 to disable limits (not recommended in production).
Source: middleware/decompress.go:65
+ToMiddleware converts DecompressConfig to middleware or returns an error for invalid configuration
Source: middleware/decompress.go:35
+Decompressor is used to get the sync.Pool used by the middleware to get Gzip readers
type Decompressor interface {
+ // contains filtered or unexported methods
+}Source: middleware/decompress.go:40
+DefaultGzipDecompressPool is the default implementation of Decompressor interface
type DefaultGzipDecompressPool struct {
+}Source: middleware/rate_limiter.go:52
+Extractor is used to extract data from *echo.Context
type Extractor func(c *echo.Context) (string, error)Source: middleware/extractor.go:21
+ExtractorSource is type to indicate source for extracted value
type ExtractorSource stringSource: middleware/compress.go:25
+GzipConfig defines the config for Gzip middleware.
type GzipConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Gzip compression level.
+ // Optional. Default value -1.
+ Level int
+
+ // Length threshold before gzip compression is applied.
+ // Optional. Default value 0.
+ //
+ // Most of the time you will not need to change the default. Compressing
+ // a short response might increase the transmitted data because of the
+ // gzip format overhead. Compressing the response will also consume CPU
+ // and time on the server and the client (for decompressing). Depending on
+ // your use case such a threshold might be useful.
+ //
+ // See also:
+ // https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
+ MinLength int
+}Skipper Skipper Skipper defines a function to skip middleware.
Level int Gzip compression level. +Optional. Default value -1.
MinLength int Length threshold before gzip compression is applied. +Optional. Default value 0.
+Most of the time you will not need to change the default. Compressing +a short response might increase the transmitted data because of the +gzip format overhead. Compressing the response will also consume CPU +and time on the server and the client (for decompressing). Depending on +your use case such a threshold might be useful.
+Source: middleware/compress.go:69
+ToMiddleware converts GzipConfig to middleware or returns an error for invalid configuration
Source: middleware/key_auth.go:19
+KeyAuthConfig defines the config for KeyAuth middleware.
+SECURITY: The Validator function is responsible for securely comparing API keys. +See KeyAuthValidator documentation for guidance on preventing timing attacks.
type KeyAuthConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // KeyLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
+ // to extract key from the request.
+ // Optional. Default value "header:Authorization:Bearer ".
+ // Possible values:
+ // - "header:<name>" or "header:<name>:<cut-prefix>"
+ // `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header
+ // value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we
+ // want to cut is `<auth-scheme> ` note the space at the end.
+ // In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `.
+ // - "query:<name>"
+ // - "form:<name>"
+ // - "cookie:<name>"
+ // Multiple sources example:
+ // - "header:Authorization,header:X-Api-Key"
+ KeyLookup string
+
+ // AllowedCheckLimit set how many KeyLookup values are allowed to be checked. This is
+ // useful environments like corporate test environments with application proxies restricting
+ // access to environment with their own auth scheme.
+ AllowedCheckLimit uint
+
+ // Validator is a function to validate key.
+ // Required.
+ Validator KeyAuthValidator
+
+ // ErrorHandler defines a function which is executed when all lookups have been done and none of them passed Validator
+ // function. ErrorHandler is executed with last missing (ErrExtractionValueMissing) or an invalid key.
+ // It may be used to define a custom error.
+ //
+ // Note: when error handler swallows the error (returns nil) middleware continues handler chain execution towards handler.
+ // This is useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users
+ // In that case you can use ErrorHandler to set default public auth value to request and continue with handler chain.
+ ErrorHandler KeyAuthErrorHandler
+
+ // ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to
+ // ignore the error (by returning `nil`).
+ // This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality.
+ // In that case you can use ErrorHandler to set a default public key auth value in the request context
+ // and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then.
+ ContinueOnIgnoredError bool
+}Skipper Skipper Skipper defines a function to skip middleware.
KeyLookup string KeyLookup is a string in the form of "
<cut-prefix> is argument value to cut/trim prefix of the extracted value. This is useful if header
+ value has static prefix like Authorization: <auth-scheme> <authorisation-parameters> where part that we
+ want to cut is <auth-scheme> note the space at the end.
+ In case of basic authentication Authorization: Basic <credentials> prefix we want to remove is Basic .AllowedCheckLimit uint AllowedCheckLimit set how many KeyLookup values are allowed to be checked. This is +useful environments like corporate test environments with application proxies restricting +access to environment with their own auth scheme.
Validator KeyAuthValidator Validator is a function to validate key. +Required.
ErrorHandler KeyAuthErrorHandler ErrorHandler defines a function which is executed when all lookups have been done and none of them passed Validator +function. ErrorHandler is executed with last missing (ErrExtractionValueMissing) or an invalid key. +It may be used to define a custom error.
+Note: when error handler swallows the error (returns nil) middleware continues handler chain execution towards handler. +This is useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users +In that case you can use ErrorHandler to set default public auth value to request and continue with handler chain.
ContinueOnIgnoredError bool ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to
+ignore the error (by returning nil).
+This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality.
+In that case you can use ErrorHandler to set a default public key auth value in the request context
+and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then.
Source: middleware/key_auth.go:138
+ToMiddleware converts KeyAuthConfig to middleware or returns an error for invalid configuration
Source: middleware/key_auth.go:103
+KeyAuthErrorHandler defines a function which is executed for an invalid key.
type KeyAuthErrorHandler func(c *echo.Context, err error) errorSource: middleware/key_auth.go:100
+KeyAuthValidator defines a function to validate KeyAuth credentials.
+SECURITY WARNING: To prevent timing attacks that could allow attackers to enumerate +valid API keys, validator implementations MUST use constant-time comparison. +Use crypto/subtle.ConstantTimeCompare instead of standard string equality (==) +or switch statements.
+Example of SECURE implementation:
+import "crypto/subtle"
+
+validator := func(c *echo.Context, key string, source ExtractorSource) (bool, error) {
+ // Fetch valid keys from database/config
+ validKeys := []string{"key1", "key2", "key3"}
+
+ for _, validKey := range validKeys {
+ // Use constant-time comparison to prevent timing attacks
+ if subtle.ConstantTimeCompare([]byte(key), []byte(validKey)) == 1 {
+ return true, nil
+ }
+ }
+ return false, nil
+}Example of INSECURE implementation (DO NOT USE):
+// VULNERABLE TO TIMING ATTACKS - DO NOT USE
+validator := func(c *echo.Context, key string, source ExtractorSource) (bool, error) {
+ switch key { // Timing leak!
+ case "valid-key":
+ return true, nil
+ default:
+ return false, nil
+ }
+}type KeyAuthValidator func(c *echo.Context, key string, source ExtractorSource) (bool, error)Source: middleware/method_override.go:13
+MethodOverrideConfig defines the config for MethodOverride middleware.
type MethodOverrideConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Getter is a function that gets overridden method from the request.
+ // Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride).
+ Getter MethodOverrideGetter
+}Skipper Skipper Skipper defines a function to skip middleware.
Getter MethodOverrideGetter Getter is a function that gets overridden method from the request. +Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride).
Source: middleware/method_override.go:46
+ToMiddleware converts MethodOverrideConfig to middleware or returns an error for invalid configuration
Source: middleware/method_override.go:23
+MethodOverrideGetter is a function that gets overridden method from the request
type MethodOverrideGetter func(c *echo.Context) stringSource: middleware/recover.go:92
+PanicStackError is an error type that wraps an error along with its stack trace. +It is returned when config.DisablePrintStack is set to false.
type PanicStackError struct {
+ Stack []byte
+ Err error
+}Stack []byte Err error Source: middleware/proxy.go:100
+ProxyBalancer defines an interface to implement a load balancing technique.
type ProxyBalancer interface {
+ AddTarget(target *ProxyTarget) bool
+ RemoveTarget(targetName string) bool
+ Next(c *echo.Context) (*ProxyTarget, error)
+}AddTarget func(target *ProxyTarget) bool RemoveTarget func(targetName string) bool Next func(c *echo.Context) (*ProxyTarget, error) Source: middleware/proxy.go:29
+ProxyConfig defines the config for Proxy middleware.
type ProxyConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Balancer defines a load balancing technique.
+ // Required.
+ Balancer ProxyBalancer
+
+ // RetryCount defines the number of times a failed proxied request should be retried
+ // using the next available ProxyTarget. Defaults to 0, meaning requests are never retried.
+ RetryCount int
+
+ // RetryFilter defines a function used to determine if a failed request to a
+ // ProxyTarget should be retried. The RetryFilter will only be called when the number
+ // of previous retries is less than RetryCount. If the function returns true, the
+ // request will be retried. The provided error indicates the reason for the request
+ // failure. When the ProxyTarget is unavailable, the error will be an instance of
+ // echo.HTTPError with a code of http.StatusBadGateway. In all other cases, the error
+ // will indicate an internal error in the Proxy middleware. When a RetryFilter is not
+ // specified, all requests that fail with http.StatusBadGateway will be retried. A custom
+ // RetryFilter can be provided to only retry specific requests. Note that RetryFilter is
+ // only called when the request to the target fails, or an internal error in the Proxy
+ // middleware has occurred. Successful requests that return a non-200 response code cannot
+ // be retried.
+ RetryFilter func(c *echo.Context, e error) bool
+
+ // ErrorHandler defines a function which can be used to return custom errors from
+ // the Proxy middleware. ErrorHandler is only invoked when there has been
+ // either an internal error in the Proxy middleware or the ProxyTarget is
+ // unavailable. Due to the way requests are proxied, ErrorHandler is not invoked
+ // when a ProxyTarget returns a non-200 response. In these cases, the response
+ // is already written so errors cannot be modified. ErrorHandler is only
+ // invoked after all retry attempts have been exhausted.
+ ErrorHandler func(c *echo.Context, err error) error
+
+ // Rewrite defines URL path rewrite rules. The values captured in asterisk can be
+ // retrieved by index e.g. $1, $2 and so on.
+ // Examples:
+ // "/old": "/new",
+ // "/api/*": "/$1",
+ // "/js/*": "/public/javascripts/$1",
+ // "/users/*/orders/*": "/user/$1/order/$2",
+ Rewrite map[string]string
+
+ // RegexRewrite defines rewrite rules using regexp.Rexexp with captures
+ // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on.
+ // Example:
+ // "^/old/[0.9]+/": "/new",
+ // "^/api/.+?/(.*)": "/v2/$1",
+ RegexRewrite map[*regexp.Regexp]string
+
+ // Context key to store selected ProxyTarget into context.
+ // Optional. Default value "target".
+ ContextKey string
+
+ // To customize the transport to remote.
+ // Examples: If custom TLS certificates are required.
+ Transport http.RoundTripper
+
+ // ModifyResponse defines function to modify response from ProxyTarget.
+ ModifyResponse func(*http.Response) error
+}Skipper Skipper Skipper defines a function to skip middleware.
Balancer ProxyBalancer Balancer defines a load balancing technique. +Required.
RetryCount int RetryCount defines the number of times a failed proxied request should be retried +using the next available ProxyTarget. Defaults to 0, meaning requests are never retried.
RetryFilter func(c *echo.Context, e error) bool RetryFilter defines a function used to determine if a failed request to a +ProxyTarget should be retried. The RetryFilter will only be called when the number +of previous retries is less than RetryCount. If the function returns true, the +request will be retried. The provided error indicates the reason for the request +failure. When the ProxyTarget is unavailable, the error will be an instance of +echo.HTTPError with a code of http.StatusBadGateway. In all other cases, the error +will indicate an internal error in the Proxy middleware. When a RetryFilter is not +specified, all requests that fail with http.StatusBadGateway will be retried. A custom +RetryFilter can be provided to only retry specific requests. Note that RetryFilter is +only called when the request to the target fails, or an internal error in the Proxy +middleware has occurred. Successful requests that return a non-200 response code cannot +be retried.
ErrorHandler func(c *echo.Context, err error) error ErrorHandler defines a function which can be used to return custom errors from +the Proxy middleware. ErrorHandler is only invoked when there has been +either an internal error in the Proxy middleware or the ProxyTarget is +unavailable. Due to the way requests are proxied, ErrorHandler is not invoked +when a ProxyTarget returns a non-200 response. In these cases, the response +is already written so errors cannot be modified. ErrorHandler is only +invoked after all retry attempts have been exhausted.
Rewrite map[string]string Rewrite defines URL path rewrite rules. The values captured in asterisk can be +retrieved by index e.g. $1, $2 and so on. +Examples: +"/old": "/new", +"/api/": "/$1", +"/js/": "/public/javascripts/$1", +"/users//orders/": "/user/$1/order/$2",
RegexRewrite map[*regexp.Regexp]string RegexRewrite defines rewrite rules using regexp.Rexexp with captures +Every capture group in the values can be retrieved by index e.g. $1, $2 and so on. +Example: +"^/old/[0.9]+/": "/new", +"^/api/.+?/(.*)": "/v2/$1",
ContextKey string Context key to store selected ProxyTarget into context. +Optional. Default value "target".
Transport http.RoundTripper To customize the transport to remote. +Examples: If custom TLS certificates are required.
ModifyResponse func(*http.Response) error ModifyResponse defines function to modify response from ProxyTarget.
Source: middleware/proxy.go:306
+ToMiddleware converts ProxyConfig to middleware or returns an error for invalid configuration
Source: middleware/proxy.go:93
+ProxyTarget defines the upstream target.
type ProxyTarget struct {
+ Name string
+ URL *url.URL
+ Meta map[string]any
+}Name string URL *url.URL Meta map[string]any Source: middleware/rate_limiter.go:38
+RateLimiterConfig defines the configuration for the rate limiter
type RateLimiterConfig struct {
+ Skipper Skipper
+ BeforeFunc BeforeFunc
+ // IdentifierExtractor uses *echo.Context to extract the identifier for a visitor
+ IdentifierExtractor Extractor
+ // Store defines a store for the rate limiter
+ Store RateLimiterStore
+ // ErrorHandler provides a handler to be called when IdentifierExtractor returns an error
+ ErrorHandler func(c *echo.Context, err error) error
+ // DenyHandler provides a handler to be called when RateLimiter denies access
+ DenyHandler func(c *echo.Context, identifier string, err error) error
+}Skipper Skipper BeforeFunc BeforeFunc IdentifierExtractor Extractor IdentifierExtractor uses *echo.Context to extract the identifier for a visitor
Store RateLimiterStore Store defines a store for the rate limiter
ErrorHandler func(c *echo.Context, err error) error ErrorHandler provides a handler to be called when IdentifierExtractor returns an error
DenyHandler func(c *echo.Context, identifier string, err error) error DenyHandler provides a handler to be called when RateLimiter denies access
Source: middleware/rate_limiter.go:124
+ToMiddleware converts RateLimiterConfig to middleware or returns an error for invalid configuration
Source: middleware/rate_limiter.go:170
+RateLimiterMemoryStore is the built-in store implementation for RateLimiter
type RateLimiterMemoryStore struct {
+ // contains filtered or unexported fields
+}Source: middleware/rate_limiter.go:256
+Allow implements RateLimiterStore.Allow
Source: middleware/rate_limiter.go:263
+AllowContext implements RateLimiterStoreContext: it makes the allow/deny decision +and sets the X-RateLimit-* (and Retry-After when denied) response headers.
Source: middleware/rate_limiter.go:244
+RateLimiterMemoryStoreConfig represents configuration for RateLimiterMemoryStore
type RateLimiterMemoryStoreConfig struct {
+ Rate float64 // Rate of requests allowed to pass as req/s. For more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit.
+ Burst int // Burst is maximum number of requests to pass at the same moment. It additionally allows a number of requests to pass when rate limit is reached.
+ ExpiresIn time.Duration // ExpiresIn is the duration after that a rate limiter is cleaned up
+}Rate float64 Rate of requests allowed to pass as req/s. For more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit.
Burst int Burst is maximum number of requests to pass at the same moment. It additionally allows a number of requests to pass when rate limit is reached.
ExpiresIn time.Duration ExpiresIn is the duration after that a rate limiter is cleaned up
Source: middleware/rate_limiter.go:25
+RateLimiterStore is the interface to be implemented by custom stores.
type RateLimiterStore interface {
+ Allow(identifier string) (bool, error)
+}Allow func(identifier string) (bool, error) Source: middleware/rate_limiter.go:33
+RateLimiterStoreContext is an optional interface a RateLimiterStore may implement. +When the configured store implements it, the rate limiter calls AllowContext +(with the request context) instead of Allow, allowing the store to set response +headers such as Retry-After or X-RateLimit-* on the allow/deny decision.
type RateLimiterStoreContext interface {
+ AllowContext(c *echo.Context, identifier string) (bool, error)
+}AllowContext func(c *echo.Context, identifier string) (bool, error) Source: middleware/recover.go:15
+RecoverConfig defines the config for Recover middleware.
type RecoverConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Size of the stack to be printed.
+ // Optional. Default value 4KB.
+ StackSize int
+
+ // DisableStackAll disables formatting stack traces of all other goroutines
+ // into buffer after the trace for the current goroutine.
+ // Optional. Default value false.
+ DisableStackAll bool
+
+ // DisablePrintStack disables printing stack trace.
+ // Optional. Default value as false.
+ DisablePrintStack bool
+}Skipper Skipper Skipper defines a function to skip middleware.
StackSize int Size of the stack to be printed. +Optional. Default value 4KB.
DisableStackAll bool DisableStackAll disables formatting stack traces of all other goroutines +into buffer after the trace for the current goroutine. +Optional. Default value false.
DisablePrintStack bool DisablePrintStack disables printing stack trace. +Optional. Default value as false.
Source: middleware/recover.go:53
+ToMiddleware converts RecoverConfig to middleware or returns an error for invalid configuration
Source: middleware/redirect.go:15
+RedirectConfig defines the config for Redirect middleware.
type RedirectConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper
+
+ // Status code to be used when redirecting the request.
+ // Optional. Default value http.StatusMovedPermanently.
+ Code int
+ // contains filtered or unexported fields
+}Skipper Skipper defines a function to skip middleware.
Code int Status code to be used when redirecting the request. +Optional. Default value http.StatusMovedPermanently.
Source: middleware/redirect.go:119
+ToMiddleware converts RedirectConfig to middleware or returns an error for invalid configuration
Source: middleware/slash.go:80
+RemoveTrailingSlashConfig is the middleware config for removing trailing slash from the request.
type RemoveTrailingSlashConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Status code to be used when redirecting the request.
+ // Optional, but when provided the request is redirected using this code.
+ RedirectCode int
+}Skipper Skipper Skipper defines a function to skip middleware.
RedirectCode int Status code to be used when redirecting the request. +Optional, but when provided the request is redirected using this code.
Source: middleware/slash.go:103
+ToMiddleware converts RemoveTrailingSlashConfig to middleware or returns an error for invalid configuration
Source: middleware/request_id.go:11
+RequestIDConfig defines the config for RequestID middleware.
type RequestIDConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Generator defines a function to generate an ID.
+ // Optional. Default value random.String(32).
+ Generator func() string
+
+ // RequestIDHandler defines a function which is executed for a request id.
+ RequestIDHandler func(c *echo.Context, requestID string)
+
+ // TargetHeader defines what header to look for to populate the id.
+ // Optional. Default value is `X-Request-Id`
+ TargetHeader string
+}Skipper Skipper Skipper defines a function to skip middleware.
Generator func() string Generator defines a function to generate an ID. +Optional. Default value random.String(32).
RequestIDHandler func(c *echo.Context, requestID string) RequestIDHandler defines a function which is executed for a request id.
TargetHeader string TargetHeader defines what header to look for to populate the id.
+Optional. Default value is X-Request-Id
Source: middleware/request_id.go:42
+ToMiddleware converts RequestIDConfig to middleware or returns an error for invalid configuration
Source: middleware/request_logger.go:124
+RequestLoggerConfig is configuration for Request Logger middleware.
type RequestLoggerConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // BeforeNextFunc defines a function that is called before next middleware or handler is called in chain.
+ BeforeNextFunc func(c *echo.Context)
+ // LogValuesFunc defines a function that is called with values extracted by logger from request/response.
+ // Mandatory.
+ LogValuesFunc func(c *echo.Context, v RequestLoggerValues) error
+
+ // HandleError instructs logger to call global error handler when next middleware/handler returns an error.
+ // This is useful when you have custom error handler that can decide to use different status codes.
+ //
+ // A side-effect of calling global error handler is that now Response has been committed and sent to the client
+ // and middlewares up in chain can not change Response status code or response body.
+ HandleError bool
+
+ // LogLatency instructs logger to record duration it took to execute rest of the handler chain (next(c) call).
+ LogLatency bool
+ // LogProtocol instructs logger to extract request protocol (i.e. `HTTP/1.1` or `HTTP/2`)
+ LogProtocol bool
+ // LogRemoteIP instructs logger to extract request remote IP. See `echo.Context.RealIP()` for implementation details.
+ LogRemoteIP bool
+ // LogHost instructs logger to extract request host value (i.e. `example.com`)
+ LogHost bool
+ // LogMethod instructs logger to extract request method value (i.e. `GET` etc)
+ LogMethod bool
+ // LogURI instructs logger to extract request URI (i.e. `/list?lang=en&page=1`)
+ LogURI bool
+ // LogURIPath instructs logger to extract request URI path part (i.e. `/list`)
+ LogURIPath bool
+ // LogRoutePath instructs logger to extract route path part to which request was matched to (i.e. `/user/:id`)
+ LogRoutePath bool
+ // LogRequestID instructs logger to extract request ID from request `X-Request-ID` header or response if request did not have value.
+ LogRequestID bool
+ // LogReferer instructs logger to extract request referer values.
+ LogReferer bool
+ // LogUserAgent instructs logger to extract request user agent values.
+ LogUserAgent bool
+ // LogStatus instructs logger to extract response status code. If handler chain returns an error,
+ // the status code is extracted from the error satisfying echo.StatusCoder interface.
+ LogStatus bool
+ // LogContentLength instructs logger to extract content length header value. Note: this value could be different from
+ // actual request body size as it could be spoofed etc.
+ LogContentLength bool
+ // LogResponseSize instructs logger to extract response content length value. Note: when used with Gzip middleware
+ // this value may not be always correct.
+ LogResponseSize bool
+ // LogHeaders instructs logger to extract given list of headers from request. Note: request can contain more than
+ // one header with same value so slice of values is been logger for each given header.
+ //
+ // Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header
+ // names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding".
+ LogHeaders []string
+ // LogQueryParams instructs logger to extract given list of query parameters from request URI. Note: request can
+ // contain more than one query parameter with same name so slice of values is been logger for each given query param name.
+ LogQueryParams []string
+ // LogFormValues instructs logger to extract given list of form values from request body+URI. Note: request can
+ // contain more than one form value with same name so slice of values is been logger for each given form value name.
+ LogFormValues []string
+ // contains filtered or unexported fields
+}Skipper Skipper Skipper defines a function to skip middleware.
BeforeNextFunc func(c *echo.Context) BeforeNextFunc defines a function that is called before next middleware or handler is called in chain.
LogValuesFunc func(c *echo.Context, v RequestLoggerValues) error LogValuesFunc defines a function that is called with values extracted by logger from request/response. +Mandatory.
HandleError bool HandleError instructs logger to call global error handler when next middleware/handler returns an error. +This is useful when you have custom error handler that can decide to use different status codes.
+A side-effect of calling global error handler is that now Response has been committed and sent to the client +and middlewares up in chain can not change Response status code or response body.
LogLatency bool LogLatency instructs logger to record duration it took to execute rest of the handler chain (next(c) call).
LogProtocol bool LogProtocol instructs logger to extract request protocol (i.e. HTTP/1.1 or HTTP/2)
LogRemoteIP bool LogRemoteIP instructs logger to extract request remote IP. See echo.Context.RealIP() for implementation details.
LogHost bool LogHost instructs logger to extract request host value (i.e. example.com)
LogMethod bool LogMethod instructs logger to extract request method value (i.e. GET etc)
LogURI bool LogURI instructs logger to extract request URI (i.e. /list?lang=en&page=1)
LogURIPath bool LogURIPath instructs logger to extract request URI path part (i.e. /list)
LogRoutePath bool LogRoutePath instructs logger to extract route path part to which request was matched to (i.e. /user/:id)
LogRequestID bool LogRequestID instructs logger to extract request ID from request X-Request-ID header or response if request did not have value.
LogReferer bool LogReferer instructs logger to extract request referer values.
LogUserAgent bool LogUserAgent instructs logger to extract request user agent values.
LogStatus bool LogStatus instructs logger to extract response status code. If handler chain returns an error, +the status code is extracted from the error satisfying echo.StatusCoder interface.
LogContentLength bool LogContentLength instructs logger to extract content length header value. Note: this value could be different from +actual request body size as it could be spoofed etc.
LogResponseSize bool LogResponseSize instructs logger to extract response content length value. Note: when used with Gzip middleware +this value may not be always correct.
LogHeaders []string LogHeaders instructs logger to extract given list of headers from request. Note: request can contain more than +one header with same value so slice of values is been logger for each given header.
+Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header +names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding".
LogQueryParams []string LogQueryParams instructs logger to extract given list of query parameters from request URI. Note: request can +contain more than one query parameter with same name so slice of values is been logger for each given query param name.
LogFormValues []string LogFormValues instructs logger to extract given list of form values from request body+URI. Note: request can +contain more than one form value with same name so slice of values is been logger for each given form value name.
Source: middleware/request_logger.go:246
+ToMiddleware converts RequestLoggerConfig into middleware or returns an error for invalid configuration.
Source: middleware/request_logger.go:189
+RequestLoggerValues contains extracted values from logger.
type RequestLoggerValues struct {
+ // StartTime is time recorded before next middleware/handler is executed.
+ StartTime time.Time
+ // Latency is duration it took to execute rest of the handler chain (next(c) call).
+ Latency time.Duration
+ // Protocol is request protocol (i.e. `HTTP/1.1` or `HTTP/2`)
+ Protocol string
+ // RemoteIP is request remote IP. See `echo.Context.RealIP()` for implementation details.
+ RemoteIP string
+ // Host is request host value (i.e. `example.com`)
+ Host string
+ // Method is request method value (i.e. `GET` etc)
+ Method string
+ // URI is request URI (i.e. `/list?lang=en&page=1`)
+ URI string
+ // URIPath is request URI path part (i.e. `/list`)
+ URIPath string
+ // RoutePath is route path part to which request was matched to (i.e. `/user/:id`)
+ RoutePath string
+ // RequestID is request ID from request `X-Request-ID` header or response if request did not have value.
+ RequestID string
+ // Referer is request referer values.
+ Referer string
+ // UserAgent is request user agent values.
+ UserAgent string
+ // Status is a response status code. When the handler returns an error satisfying echo.StatusCoder interface, then code from it.
+ Status int
+ // Error is error returned from executed handler chain.
+ Error error
+ // ContentLength is content length header value. Note: this value could be different from actual request body size
+ // as it could be spoofed etc.
+ ContentLength string
+ // ResponseSize is response content length value. Note: when used with Gzip middleware this value may not be always correct.
+ ResponseSize int64
+ // Headers are list of headers from request. Note: request can contain more than one header with same value so slice
+ // of values is what will be returned/logged for each given header.
+ // Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header
+ // names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding".
+ Headers map[string][]string
+ // QueryParams are list of query parameters from request URI. Note: request can contain more than one query parameter
+ // with same name so slice of values is what will be returned/logged for each given query param name.
+ QueryParams map[string][]string
+ // FormValues are list of form values from request body+URI. Note: request can contain more than one form value with
+ // same name so slice of values is what will be returned/logged for each given form value name.
+ FormValues map[string][]string
+}StartTime time.Time StartTime is time recorded before next middleware/handler is executed.
Latency time.Duration Latency is duration it took to execute rest of the handler chain (next(c) call).
Protocol string Protocol is request protocol (i.e. HTTP/1.1 or HTTP/2)
RemoteIP string RemoteIP is request remote IP. See echo.Context.RealIP() for implementation details.
Host string Host is request host value (i.e. example.com)
Method string Method is request method value (i.e. GET etc)
URI string URI is request URI (i.e. /list?lang=en&page=1)
URIPath string URIPath is request URI path part (i.e. /list)
RoutePath string RoutePath is route path part to which request was matched to (i.e. /user/:id)
RequestID string RequestID is request ID from request X-Request-ID header or response if request did not have value.
Referer string Referer is request referer values.
UserAgent string UserAgent is request user agent values.
Status int Status is a response status code. When the handler returns an error satisfying echo.StatusCoder interface, then code from it.
Error error Error is error returned from executed handler chain.
ContentLength string ContentLength is content length header value. Note: this value could be different from actual request body size +as it could be spoofed etc.
ResponseSize int64 ResponseSize is response content length value. Note: when used with Gzip middleware this value may not be always correct.
Headers map[string][]string Headers are list of headers from request. Note: request can contain more than one header with same value so slice +of values is what will be returned/logged for each given header. +Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header +names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding".
QueryParams map[string][]string QueryParams are list of query parameters from request URI. Note: request can contain more than one query parameter +with same name so slice of values is what will be returned/logged for each given query param name.
FormValues map[string][]string FormValues are list of form values from request body+URI. Note: request can contain more than one form value with +same name so slice of values is what will be returned/logged for each given form value name.
Source: middleware/rewrite.go:15
+RewriteConfig defines the config for Rewrite middleware.
type RewriteConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Rules defines the URL path rewrite rules. The values captured in asterisk can be
+ // retrieved by index e.g. $1, $2 and so on.
+ // Example:
+ // "/old": "/new",
+ // "/api/*": "/$1",
+ // "/js/*": "/public/javascripts/$1",
+ // "/users/*/orders/*": "/user/$1/order/$2",
+ // Required.
+ Rules map[string]string
+
+ // RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures
+ // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on.
+ // Example:
+ // "^/old/[0.9]+/": "/new",
+ // "^/api/.+?/(.*)": "/v2/$1",
+ RegexRules map[*regexp.Regexp]string
+}Skipper Skipper Skipper defines a function to skip middleware.
Rules map[string]string Rules defines the URL path rewrite rules. The values captured in asterisk can be +retrieved by index e.g. $1, $2 and so on. +Example: +"/old": "/new", +"/api/": "/$1", +"/js/": "/public/javascripts/$1", +"/users//orders/": "/user/$1/order/$2", +Required.
RegexRules map[*regexp.Regexp]string RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures +Every capture group in the values can be retrieved by index e.g. $1, $2 and so on. +Example: +"^/old/[0.9]+/": "/new", +"^/api/.+?/(.*)": "/v2/$1",
Source: middleware/rewrite.go:54
+ToMiddleware converts RewriteConfig to middleware or returns an error for invalid configuration
Source: middleware/secure.go:13
+SecureConfig defines the config for Secure middleware.
type SecureConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // XSSProtection provides protection against cross-site scripting attack (XSS)
+ // by setting the `X-XSS-Protection` header.
+ // Optional. Default value "1; mode=block".
+ XSSProtection string
+
+ // ContentTypeNosniff provides protection against overriding Content-Type
+ // header by setting the `X-Content-Type-Options` header.
+ // Optional. Default value "nosniff".
+ ContentTypeNosniff string
+
+ // XFrameOptions can be used to indicate whether or not a browser should
+ // be allowed to render a page in a <frame>, <iframe> or <object> .
+ // Sites can use this to avoid clickjacking attacks, by ensuring that their
+ // content is not embedded into other sites.provides protection against
+ // clickjacking.
+ // Optional. Default value "SAMEORIGIN".
+ // Possible values:
+ // - "SAMEORIGIN" - The page can only be displayed in a frame on the same origin as the page itself.
+ // - "DENY" - The page cannot be displayed in a frame, regardless of the site attempting to do so.
+ // - "ALLOW-FROM uri" - The page can only be displayed in a frame on the specified origin.
+ XFrameOptions string
+
+ // HSTSMaxAge sets the `Strict-Transport-Security` header to indicate how
+ // long (in seconds) browsers should remember that this site is only to
+ // be accessed using HTTPS. This reduces your exposure to some SSL-stripping
+ // man-in-the-middle (MITM) attacks.
+ // Optional. Default value 0.
+ HSTSMaxAge int
+
+ // HSTSExcludeSubdomains won't include subdomains tag in the `Strict Transport Security`
+ // header, excluding all subdomains from security policy. It has no effect
+ // unless HSTSMaxAge is set to a non-zero value.
+ // Optional. Default value false.
+ HSTSExcludeSubdomains bool
+
+ // ContentSecurityPolicy sets the `Content-Security-Policy` header providing
+ // security against cross-site scripting (XSS), clickjacking and other code
+ // injection attacks resulting from execution of malicious content in the
+ // trusted web page context.
+ // Optional. Default value "".
+ ContentSecurityPolicy string
+
+ // CSPReportOnly would use the `Content-Security-Policy-Report-Only` header instead
+ // of the `Content-Security-Policy` header. This allows iterative updates of the
+ // content security policy by only reporting the violations that would
+ // have occurred instead of blocking the resource.
+ // Optional. Default value false.
+ CSPReportOnly bool
+
+ // HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security`
+ // header, which enables the domain to be included in the HSTS preload list
+ // maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
+ // Optional. Default value false.
+ HSTSPreloadEnabled bool
+
+ // ReferrerPolicy sets the `Referrer-Policy` header providing security against
+ // leaking potentially sensitive request paths to third parties.
+ // Optional. Default value "".
+ ReferrerPolicy string
+}Skipper Skipper Skipper defines a function to skip middleware.
XSSProtection string XSSProtection provides protection against cross-site scripting attack (XSS)
+by setting the X-XSS-Protection header.
+Optional. Default value "1; mode=block".
ContentTypeNosniff string ContentTypeNosniff provides protection against overriding Content-Type
+header by setting the X-Content-Type-Options header.
+Optional. Default value "nosniff".
XFrameOptions string XFrameOptions can be used to indicate whether or not a browser should +be allowed to render a page in a ,
HSTSMaxAge int HSTSMaxAge sets the Strict-Transport-Security header to indicate how
+long (in seconds) browsers should remember that this site is only to
+be accessed using HTTPS. This reduces your exposure to some SSL-stripping
+man-in-the-middle (MITM) attacks.
+Optional. Default value 0.
HSTSExcludeSubdomains bool HSTSExcludeSubdomains won't include subdomains tag in the Strict Transport Security
+header, excluding all subdomains from security policy. It has no effect
+unless HSTSMaxAge is set to a non-zero value.
+Optional. Default value false.
ContentSecurityPolicy string ContentSecurityPolicy sets the Content-Security-Policy header providing
+security against cross-site scripting (XSS), clickjacking and other code
+injection attacks resulting from execution of malicious content in the
+trusted web page context.
+Optional. Default value "".
CSPReportOnly bool CSPReportOnly would use the Content-Security-Policy-Report-Only header instead
+of the Content-Security-Policy header. This allows iterative updates of the
+content security policy by only reporting the violations that would
+have occurred instead of blocking the resource.
+Optional. Default value false.
HSTSPreloadEnabled bool HSTSPreloadEnabled will add the preload tag in the Strict Transport Security
+header, which enables the domain to be included in the HSTS preload list
+maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
+Optional. Default value false.
ReferrerPolicy string ReferrerPolicy sets the Referrer-Policy header providing security against
+leaking potentially sensitive request paths to third parties.
+Optional. Default value "".
Source: middleware/secure.go:101
+ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration
Source: middleware/middleware.go:16
+Skipper defines a function to skip middleware. Returning true skips processing the middleware.
type Skipper func(c *echo.Context) boolSource: middleware/static.go:24
+StaticConfig defines the config for Static middleware.
type StaticConfig struct {
+ // Skipper defines a function to skip middleware.
+ Skipper Skipper
+
+ // Root directory from where the static content is served (relative to given Filesystem).
+ // `Root: "."` means root folder from Filesystem.
+ // Required.
+ Root string
+
+ // Filesystem provides access to the static content.
+ // Optional. Defaults to echo.Filesystem (serves files from `.` folder where executable is started)
+ Filesystem fs.FS
+
+ // Index file for serving a directory.
+ // Optional. Default value "index.html".
+ Index string
+
+ // Enable HTML5 mode by forwarding all not-found requests to root so that
+ // SPA (single-page application) can handle the routing.
+ // Optional. Default value false.
+ HTML5 bool
+
+ // Enable directory browsing.
+ // Optional. Default value false.
+ Browse bool
+
+ // Enable ignoring of the base of the URL path.
+ // Example: when assigning a static middleware to a non root path group,
+ // the filesystem path is not doubled
+ // Optional. Default value false.
+ IgnoreBase bool
+
+ // Deprecated: this field is ignored, use EnablePathUnescaping instead. DisablePathUnescaping will be removed in a future version.
+ // Note: previously the zero value (false) enabled unescaping, which was the unsafe default.
+ DisablePathUnescaping bool
+
+ // EnablePathUnescaping enables path parameter (param: *) unescaping.
+ // Default false (safe): encoded slashes (%2f) in the wildcard param are NOT decoded,
+ // preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/* route guard by
+ // not matching that route but having its wildcard param decoded to admin/private.txt.
+ // Set to true only when serving files whose names contain URL-encoded characters
+ // (e.g. "hello world.txt" via /hello%20world.txt) and you are not relying on
+ // route-based ACL guards to restrict access.
+ //
+ // Enabling echo.RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when
+ // using different Routes to exclude some of the files from being served.
+ // e.g. if you serve files from directory as such and use different route to exclude some of the files from being served.
+ // 0. given folder structure:
+ // public/
+ // public/index.html
+ // public/admin/private.txt
+ // 1. share `public/` folder contents from the server root with `e.Static("/", "public")`
+ // 2. naively assume that everything under /admin folder is now forbidden
+ // e.GET("/admin/*", func(c *Context) error { return echo.ErrForbidden })
+ // Then request to `/assets/../admin%2fprivate.txt` will be served as router does not match it to guarded route.
+ EnablePathUnescaping bool
+
+ // DirectoryListTemplate is template to list directory contents
+ // Optional. Default to `directoryListHTMLTemplate` constant below.
+ DirectoryListTemplate string
+}Skipper Skipper Skipper defines a function to skip middleware.
Root string Root directory from where the static content is served (relative to given Filesystem).
+Root: "." means root folder from Filesystem.
+Required.
Filesystem fs.FS Filesystem provides access to the static content.
+Optional. Defaults to echo.Filesystem (serves files from . folder where executable is started)
Index string Index file for serving a directory. +Optional. Default value "index.html".
HTML5 bool Enable HTML5 mode by forwarding all not-found requests to root so that +SPA (single-page application) can handle the routing. +Optional. Default value false.
Browse bool Enable directory browsing. +Optional. Default value false.
IgnoreBase bool Enable ignoring of the base of the URL path. +Example: when assigning a static middleware to a non root path group, +the filesystem path is not doubled +Optional. Default value false.
DisablePathUnescaping bool Deprecated: this field is ignored, use EnablePathUnescaping instead. DisablePathUnescaping will be removed in a future version. +Note: previously the zero value (false) enabled unescaping, which was the unsafe default.
EnablePathUnescaping bool EnablePathUnescaping enables path parameter (param: ) unescaping. +Default false (safe): encoded slashes (%2f) in the wildcard param are NOT decoded, +preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/ route guard by +not matching that route but having its wildcard param decoded to admin/private.txt. +Set to true only when serving files whose names contain URL-encoded characters +(e.g. "hello world.txt" via /hello%20world.txt) and you are not relying on +route-based ACL guards to restrict access.
+Enabling echo.RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when +using different Routes to exclude some of the files from being served. +e.g. if you serve files from directory as such and use different route to exclude some of the files from being served. +0. given folder structure: + public/ + public/index.html + public/admin/private.txt
+public/ folder contents from the server root with e.Static("/", "public")/assets/../admin%2fprivate.txt will be served as router does not match it to guarded route.DirectoryListTemplate string DirectoryListTemplate is template to list directory contents
+Optional. Default to directoryListHTMLTemplate constant below.
Source: middleware/static.go:177
+ToMiddleware converts StaticConfig to middleware or returns an error for invalid configuration
Source: middleware/extractor.go:37
+ValueExtractorError is error type when middleware extractor is unable to extract value from lookups
type ValueExtractorError struct {
+ // contains filtered or unexported fields
+}Source: middleware/extractor.go:42
+Error returns errors text
Source: middleware/extractor.go:54
+ValuesExtractor defines a function for extracting values (keys/tokens) from the given context.
type ValuesExtractor func(c *echo.Context) ([]string, ExtractorSource, error)Source: middleware/rate_limiter.go:182
+Visitor signifies a unique user's limiter details
type Visitor struct {
+ *rate.Limiter
+ // contains filtered or unexported fields
+}*rate.Limiter import "github.com/labstack/echo/v5"
Package echo implements high performance, minimalist Go web framework.
+Example:
+package main
+
+import (
+ "log/slog"
+ "net/http"
+
+ "github.com/labstack/echo/v5"
+ "github.com/labstack/echo/v5/middleware"
+)
+
+// Handler
+func hello(c *echo.Context) error {
+ return c.String(http.StatusOK, "Hello, World!")
+}
+
+func main() {
+ // Echo instance
+ e := echo.New()
+
+ // Middleware
+ e.Use(middleware.RequestLogger())
+ e.Use(middleware.Recover())
+
+ // Routes
+ e.GET("/", hello)
+
+ // Start server
+ if err := e.Start(":8080"); err != nil {
+ slog.Error("failed to start server", "error", err)
+ }
+}Learn more at https://echo.labstack.com
TimeLayout constants for parsing Unix timestamps in different precisions.
const (
+ TimeLayoutUnixTime = TimeLayout("UnixTime") // Unix timestamp in seconds
+ TimeLayoutUnixTimeMilli = TimeLayout("UnixTimeMilli") // Unix timestamp in milliseconds
+ TimeLayoutUnixTimeNano = TimeLayout("UnixTimeNano") // Unix timestamp in nanoseconds
+)MIME types
const (
+ // MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259
+ MIMEApplicationJSON = "application/json"
+ // Deprecated: Please use MIMEApplicationJSON instead. JSON should be encoded using UTF-8 by default.
+ // No "charset" parameter is defined for this registration.
+ // Adding one really has no effect on compliant recipients.
+ // See RFC 8259, section 8.1. https://datatracker.ietf.org/doc/html/rfc8259#section-8.1n"
+ MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
+ MIMEApplicationJavaScript = "application/javascript"
+ MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
+ MIMEApplicationXML = "application/xml"
+ MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8
+ MIMETextXML = "text/xml"
+ MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8
+ MIMEApplicationForm = "application/x-www-form-urlencoded"
+ MIMEApplicationProtobuf = "application/protobuf"
+ MIMEApplicationMsgpack = "application/msgpack"
+ MIMETextHTML = "text/html"
+ MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8
+ MIMETextPlain = "text/plain"
+ MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8
+ MIMEMultipartForm = "multipart/form-data"
+ MIMEOctetStream = "application/octet-stream"
+)const (
+
+ // PROPFIND Method can be used on collection and property resources.
+ PROPFIND = "PROPFIND"
+ // REPORT Method can be used to get information about a resource, see rfc 3253
+ REPORT = "REPORT"
+ // QUERY Method is a safe, idempotent request method carrying request content (a query) in its body, see rfc 10008.
+ // It is not (yet) part of the `net/http` standard library, so Echo defines it here.
+ QUERY = "QUERY"
+ // RouteNotFound is special method type for routes handling "route not found" (404) cases
+ RouteNotFound = "echo_route_not_found"
+ // RouteAny is special method type that matches any HTTP method in request. Any has lower
+ // priority that other methods that have been registered with Router to that path.
+ RouteAny = "echo_route_any"
+)Headers
const (
+ HeaderAccept = "Accept"
+ HeaderAcceptEncoding = "Accept-Encoding"
+ // HeaderAllow is the name of the "Allow" header field used to list the set of methods
+ // advertised as supported by the target resource. Returning an Allow header is mandatory
+ // for status 405 (method not found) and useful for the OPTIONS method in responses.
+ // See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1
+ HeaderAllow = "Allow"
+ HeaderAuthorization = "Authorization"
+ HeaderContentDisposition = "Content-Disposition"
+ HeaderContentEncoding = "Content-Encoding"
+ HeaderContentLength = "Content-Length"
+ HeaderContentType = "Content-Type"
+ HeaderCookie = "Cookie"
+ HeaderSetCookie = "Set-Cookie"
+ HeaderIfModifiedSince = "If-Modified-Since"
+ HeaderLastModified = "Last-Modified"
+ HeaderLocation = "Location"
+ HeaderRetryAfter = "Retry-After"
+ HeaderUpgrade = "Upgrade"
+ HeaderVary = "Vary"
+ HeaderWWWAuthenticate = "WWW-Authenticate"
+ HeaderXForwardedFor = "X-Forwarded-For"
+ HeaderXForwardedProto = "X-Forwarded-Proto"
+ HeaderXForwardedProtocol = "X-Forwarded-Protocol"
+ HeaderXForwardedSsl = "X-Forwarded-Ssl"
+ HeaderXUrlScheme = "X-Url-Scheme"
+ HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
+ HeaderXRealIP = "X-Real-Ip"
+ HeaderXRequestID = "X-Request-Id"
+ HeaderXCorrelationID = "X-Correlation-Id"
+ HeaderXRequestedWith = "X-Requested-With"
+ HeaderServer = "Server"
+
+ // HeaderOrigin request header indicates the origin (scheme, hostname, and port) that caused the request.
+ // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
+ HeaderOrigin = "Origin"
+ HeaderCacheControl = "Cache-Control"
+ HeaderConnection = "Connection"
+
+ // Access control
+ HeaderAccessControlRequestMethod = "Access-Control-Request-Method"
+ HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
+ HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"
+ HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"
+ HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"
+ HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
+ HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"
+ HeaderAccessControlMaxAge = "Access-Control-Max-Age"
+
+ // Security
+ HeaderStrictTransportSecurity = "Strict-Transport-Security"
+ HeaderXContentTypeOptions = "X-Content-Type-Options"
+ HeaderXXSSProtection = "X-XSS-Protection"
+ HeaderXFrameOptions = "X-Frame-Options"
+ HeaderContentSecurityPolicy = "Content-Security-Policy"
+ HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
+ HeaderXCSRFToken = "X-CSRF-Token" // #nosec G101
+ HeaderReferrerPolicy = "Referrer-Policy"
+
+ // HeaderSecFetchSite fetch metadata request header indicates the relationship between a request initiator's
+ // origin and the origin of the requested resource.
+ // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site
+ HeaderSecFetchSite = "Sec-Fetch-Site"
+)const (
+ // NotFoundRouteName is name of RouteInfo returned when router did not find matching route (404: not found).
+ NotFoundRouteName = "echo_route_not_found_name"
+ // MethodNotAllowedRouteName is name of RouteInfo returned when router did not find matching method for route (405: method not allowed).
+ MethodNotAllowedRouteName = "echo_route_method_not_allowed_name"
+)const (
+ // ContextKeyHeaderAllow is set by Router for getting value for `Allow` header in later stages of handler call chain.
+ // Allow header is mandatory for status 405 (method not found) and useful for OPTIONS method requests.
+ // It is added to context only when Router does not find matching method handler for request.
+ ContextKeyHeaderAllow = "echo_header_allow"
+)const (
+ // Version of Echo
+ Version = "5.3.0"
+)The following errors can produce HTTP status code by implementing HTTPStatusCoder interface
var (
+ ErrBadRequest = &httpError{http.StatusBadRequest} // 400
+ ErrUnauthorized = &httpError{http.StatusUnauthorized} // 401
+ ErrForbidden = &httpError{http.StatusForbidden} // 403
+ ErrNotFound = &httpError{http.StatusNotFound} // 404
+ ErrMethodNotAllowed = &httpError{http.StatusMethodNotAllowed} // 405
+ ErrRequestTimeout = &httpError{http.StatusRequestTimeout} // 408
+ ErrStatusRequestEntityTooLarge = &httpError{http.StatusRequestEntityTooLarge} // 413
+ ErrUnsupportedMediaType = &httpError{http.StatusUnsupportedMediaType} // 415
+ ErrTooManyRequests = &httpError{http.StatusTooManyRequests} // 429
+ ErrInternalServerError = &httpError{http.StatusInternalServerError} // 500
+ ErrBadGateway = &httpError{http.StatusBadGateway} // 502
+ ErrServiceUnavailable = &httpError{http.StatusServiceUnavailable} // 503
+)The following errors fall into 500 (InternalServerError) category
var (
+ ErrValidatorNotRegistered = errors.New("validator not registered")
+ ErrRendererNotRegistered = errors.New("renderer not registered")
+ ErrInvalidRedirectCode = errors.New("invalid redirect status code")
+ ErrCookieNotFound = errors.New("cookie not found")
+ ErrInvalidCertOrKeyType = errors.New("invalid cert or key type, must be string or []byte")
+ ErrInvalidListenerNetwork = errors.New("invalid listener network")
+)ErrInvalidKeyType is error that is returned when the value is not castable to expected type.
var ErrInvalidKeyType = errors.New("invalid key type")ErrNonExistentKey is error that is returned when key does not exist
var ErrNonExistentKey = errors.New("non existent key")BindBody binds request body contents to bindable object +NB: then binding forms take note that this implementation uses standard library form parsing +which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm +See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm +See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm
BindHeaders binds HTTP headers to a bindable object
BindPathValues binds path parameter values to bindable object
BindQueryParams binds query params to bindable object
ContextGet retrieves a value from the context store or ErrNonExistentKey error the key is missing. +Returns ErrInvalidKeyType error if the value is not castable to type T.
ContextGetOr retrieves a value from the context store or returns a default value when the key +is missing. Returns ErrInvalidKeyType error if the value is not castable to type T.
DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response
+with status code. exposeError parameter decides if returned message will contain also error message or not
Note: DefaultHTTPErrorHandler does not log errors. Use middleware for it if errors need to be logged (separately) +Note: In case errors happens in middleware call-chain that is returning from handler (which did not return an error). +When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from +handler. Then the error that global error handler received will be ignored because we have already "committed" the +response and status code header has been sent to the client.
// SPDX-License-Identifier: MIT
+// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
+
+// run tests as external package to get real feel for API
+package echo_test
+
+import (
+ "encoding/json"
+ "fmt"
+ "github.com/labstack/echo/v5"
+ "net/http"
+ "net/http/httptest"
+)
+
+func ExampleDefaultHTTPErrorHandler() {
+ e := echo.New()
+ e.GET("/api/endpoint", func(c *echo.Context) error {
+ return &apiError{
+ Code: http.StatusBadRequest,
+ Body: map[string]any{"message": "custom error"},
+ }
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/endpoint?err=1", nil)
+ resp := httptest.NewRecorder()
+
+ e.ServeHTTP(resp, req)
+
+ fmt.Printf("%d %s", resp.Code, resp.Body.String())
+
+ // Output: 400 {"error":{"message":"custom error"}}
+}
+
+type apiError struct {
+ Code int
+ Body any
+}
+
+func (e *apiError) StatusCode() int {
+ return e.Code
+}
+
+func (e *apiError) MarshalJSON() ([]byte, error) {
+ type body struct {
+ Error any `json:"error"`
+ }
+ return json.Marshal(body{Error: e.Body})
+}
+
+func (e *apiError) Error() string {
+ return http.StatusText(e.Code)
+}
+Output:
+400 {"error":{"message":"custom error"}}ExtractIPDirect extracts an IP address using an actual IP address. +Use this if your server faces to internet directly (i.e.: uses no proxy).
ExtractIPFromRealIPHeader extracts IP address using x-real-ip header.
+Use this if you put proxy which uses this header.
ExtractIPFromXFFHeader extracts IP address using x-forwarded-for header.
+Use this if you put proxy which uses this header.
+This returns nearest untrustable IP. If all IPs are trustable, returns furthest one (i.e.: XFF[0]).
FormFieldBinder creates form field value binder +For all requests, FormFieldBinder parses the raw query from the URL and uses query params as form fields
+For POST, PUT, and PATCH requests, it also reads the request body, parses it +as a form and uses query params as form fields. Request body parameters take precedence over URL query +string values in r.Form.
+NB: when binding forms take note that this implementation uses standard library form parsing +which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm +See https://golang.org/pkg/net/http/#Request.ParseForm
FormValue extracts and parses a single form value from the request by key. +It returns the typed value and an error if binding fails. Returns ErrNonExistentKey if parameter not found.
+Empty String Handling:
+If the form field exists but has an empty value, the zero value of type T is returned
+with no error. For example, an empty form field returns (0, nil) for int types.
+This differs from standard library behavior where parsing empty strings returns errors.
+To treat empty values as errors, validate the result separately or check the raw value.See ParseValue for supported types and options
FormValueOr extracts and parses a single form value from the request by key. +Returns defaultValue if the parameter is not found or has an empty value. +Returns an error only if parsing fails or form parsing errors occur.
+Example:
+limit, err := echo.FormValueOr[int](c, "limit", 100)
+// If "limit" is missing: returns (100, nil)
+// If "limit" is "50": returns (50, nil)
+// If "limit" is "abc": returns (100, BindingError)See ParseValue for supported types and options
FormValues extracts and parses all values for a form values key as a slice. +It returns the typed slice and an error if binding any value fails. Returns ErrNonExistentKey if parameter not found.
+See ParseValues for supported types and options
FormValuesOr extracts and parses all values for a form values key as a slice. +Returns defaultValue if the parameter is not found. +Returns an error only if parsing any value fails or form parsing errors occur.
+Example:
+tags, err := echo.FormValuesOr[string](c, "tags", []string{})
+// If "tags" is missing: returns ([], nil)
+// If form parsing fails: returns (nil, error)See ParseValues for supported types and options
HandlerName returns string name for given function.
LegacyIPExtractor returns an IPExtractor that derives the client IP address +from common proxy headers, falling back to the request's remote address.
+Resolution order:
+Notes:
+Use ExtractIPFromXFFHeader or ExtractIPFromRealIPHeader instead of LegacyIPExtractor.
MustSubFS creates sub FS from current filesystem or panic on failure.
+Panic happens when fsRoot contains invalid path according to fs.ValidPath rules.
MustSubFS is helpful when dealing with embed.FS because for example //go:embed assets/images embeds files with
+paths including assets/images as their prefix. In that case use `fs := echo.MustSubFS(fs, "rootDirectory") to
+create sub fs which uses necessary prefix for directory path.
New creates an instance of Echo.
NewBindingError creates new instance of binding error
Source: router_concurrent.go:9
+NewConcurrentRouter creates concurrency safe Router which routes can be added/removed safely +even after http.Server has been started.
NewContext returns a new Context instance.
+Note: request,response and e can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway +these arguments are useful when creating context for tests and cases like that.
NewDefaultFS returns a new defaultFS instance which allows fs.FS.Open to have absolute paths as input if it matches
+then given dir as prefix.
NewHTTPError creates a new instance of HTTPError
NewResponse creates a new instance of Response.
NewRouter returns a new Router instance.
NewVirtualHostHandler creates instance of Echo that routes requests to given virtual hosts +when hosts in request does not exist in given map the request is served by returned Echo instance.
NewWithConfig creates an instance of Echo with given configuration.
ParseValue parses value to generic type
+Types that are supported:
+ParseValueOr parses value to generic type, when value is empty defaultValue is returned.
+Types that are supported:
+ParseValues parses value to generic type slice. Same types are supported as ParseValue +function but the result type is slice instead of scalar value.
+See ParseValue for supported types and options
ParseValuesOr parses value to generic type slice, when value is empty defaultValue is returned. +Same types are supported as ParseValue function but the result type is slice instead of scalar value.
+See ParseValue for supported types and options
PathParam extracts and parses a path parameter from the context by name. +It returns the typed value and an error if binding fails. Returns ErrNonExistentKey if parameter not found.
+Empty String Handling:
+If the parameter exists but has an empty value, the zero value of type T is returned
+with no error. For example, a path parameter with value "" returns (0, nil) for int types.
+This differs from standard library behavior where parsing empty strings returns errors.
+To treat empty values as errors, validate the result separately or check the raw value.See ParseValue for supported types and options
PathParamOr extracts and parses a path parameter from the context by name. +Returns defaultValue if the parameter is not found or has an empty value. +Returns an error only if parsing fails (e.g., "abc" for int type).
+Example:
+id, err := echo.PathParamOr[int](c, "id", 0)
+// If "id" is missing: returns (0, nil)
+// If "id" is "123": returns (123, nil)
+// If "id" is "abc": returns (0, BindingError)See ParseValue for supported types and options
PathValuesBinder creates path parameter value binder
QueryParam extracts and parses a single query parameter from the request by key. +It returns the typed value and an error if binding fails. Returns ErrNonExistentKey if parameter not found.
+Empty String Handling:
+If the parameter exists but has an empty value (?key=), the zero value of type T is returned
+with no error. For example, "?count=" returns (0, nil) for int types.
+This differs from standard library behavior where parsing empty strings returns errors.
+To treat empty values as errors, validate the result separately or check the raw value.Behavior Summary:
+See ParseValue for supported types and options
QueryParamOr extracts and parses a single query parameter from the request by key. +Returns defaultValue if the parameter is not found or has an empty value. +Returns an error only if parsing fails (e.g., "abc" for int type).
+Example:
+page, err := echo.QueryParamOr[int](c, "page", 1)
+// If "page" is missing: returns (1, nil)
+// If "page" is "5": returns (5, nil)
+// If "page" is "abc": returns (1, BindingError)See ParseValue for supported types and options
QueryParams extracts and parses all values for a query parameter key as a slice. +It returns the typed slice and an error if binding any value fails. Returns ErrNonExistentKey if parameter not found.
+See ParseValues for supported types and options
QueryParamsBinder creates query parameter value binder
QueryParamsOr extracts and parses all values for a query parameter key as a slice. +Returns defaultValue if the parameter is not found. +Returns an error only if parsing any value fails.
+Example:
+ids, err := echo.QueryParamsOr[int](c, "ids", []int{})
+// If "ids" is missing: returns ([], nil)
+// If "ids" is "1&ids=2": returns ([1, 2], nil)
+// If "ids" contains "abc": returns ([], BindingError)See ParseValues for supported types and options
ResolveResponseStatus returns the Response and HTTP status code that should be (or has been) sent for rw, +given an optional error.
+This function is useful for middleware and handlers that need to figure out the HTTP status +code to return based on the error that occurred or what was set in the response.
+Precedence rules:
+StaticDirectoryHandler creates handler function to serve files from provided file system +When disablePathUnescaping is set then file name from path is not unescaped and is served as is.
+Note: when disablePathUnescaping=false, the handler decodes the wildcard param before serving. +If route guards (e.g. e.GET("/admin/*", forbidden)) are used to restrict parts of the +filesystem, an encoded separator (%2F) or encoded dot-dot (%2E%2E) in the URL can resolve to +a path that the router never matched against the guard route. Enabling +RouterConfig.UseEscapedPathForMatching does NOT fix this — it changes which path the router +uses for matching but still lets path.Clean resolve ".." segments into a guarded directory. +Do not rely on route guards alone to restrict a filesystem served by this handler. +See https://github.com/labstack/echo/security/advisories/GHSA-vfp3-v2gw-7wfq
StaticFileHandler creates handler function to serve file from provided file system.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
StatusCode returns status code from err if it implements HTTPStatusCoder interface. +If err does not implement the interface, it returns 0.
TrustIPRange add trustable IP ranges using CIDR notation.
TrustLinkLocal configures if you trust link-local address (default: true).
TrustLoopback configures if you trust loopback address (default: true).
TrustPrivateNet configures if you trust private network address (default: true).
UnwrapResponse unwraps given ResponseWriter to return contexts original Echo Response. rw has to implement
+following method Unwrap() http.ResponseWriter
WrapHandler wraps http.Handler into echo.HandlerFunc.
WrapMiddleware wraps func(http.Handler) http.Handler into echo.MiddlewareFunc
AddRouteError is error returned by Router.Add containing information what actual route adding failed. Useful for +mass adding (i.e. Any() routes)
type AddRouteError struct {
+ Err error
+ Method string
+ Path string
+}Err error Method string Path string BindUnmarshaler is the interface used to wrap the UnmarshalParam method. +Types that don't implement this, but do implement encoding.TextUnmarshaler +will use that interface instead.
type BindUnmarshaler interface {
+ // UnmarshalParam decodes and assigns a value from an form or query param.
+ UnmarshalParam(param string) error
+}UnmarshalParam func(param string) error UnmarshalParam decodes and assigns a value from an form or query param.
Binder is the interface that wraps the Bind method.
type Binder interface {
+ Bind(c *Context, target any) error
+}Bind func(c *Context, target any) error BindingError represents an error that occurred while binding request data.
+Note: JSON serialization is handled by the MarshalJSON method below, not by the +struct tags (which are kept for documentation). MarshalJSON emits {"field","message"}.
type BindingError struct {
+ // Field is the field name where value binding failed
+ Field string `json:"field"`
+ *HTTPError
+ // Values of parameter that failed to bind.
+ Values []string `json:"-"`
+}Field string `json:"field"`Field is the field name where value binding failed
*HTTPError Values []string `json:"-"`Values of parameter that failed to bind.
Error returns error message
MarshalJSON implements json.Marshaler so that binding errors are serialized into +a structured response (e.g. {"field":"id","message":"..."}) rather than being +flattened to a generic message. DefaultHTTPErrorHandler routes errors that +implement json.Marshaler through their own encoding.
Config is configuration for NewWithConfig function
type Config struct {
+ // Logger is the slog logger instance used for application-wide structured logging.
+ // If not set, a default TextHandler writing to stdout is created.
+ Logger *slog.Logger
+
+ // HTTPErrorHandler is the centralized error handler that processes errors returned
+ // by handlers and middleware, converting them to appropriate HTTP responses.
+ // If not set, DefaultHTTPErrorHandler(false) is used.
+ HTTPErrorHandler HTTPErrorHandler
+
+ // Router is the HTTP request router responsible for matching URLs to handlers
+ // using a radix tree-based algorithm.
+ // If not set, NewRouter(RouterConfig{}) is used.
+ Router Router
+
+ // OnAddRoute is an optional callback hook executed when routes are registered.
+ // Useful for route validation, logging, or custom route processing.
+ // If not set, no callback is executed.
+ OnAddRoute func(route Route) error
+
+ // Filesystem is the fs.FS implementation used for serving static files.
+ // Supports os.DirFS, embed.FS, and custom implementations.
+ // If not set, defaults to current working directory.
+ Filesystem fs.FS
+
+ // Binder handles automatic data binding from HTTP requests to Go structs.
+ // Supports JSON, XML, form data, query parameters, and path parameters.
+ // If not set, DefaultBinder is used.
+ Binder Binder
+
+ // Validator provides optional struct validation after data binding.
+ // Commonly used with third-party validation libraries.
+ // If not set, Context.Validate() returns ErrValidatorNotRegistered.
+ Validator Validator
+
+ // Renderer provides template rendering for generating HTML responses.
+ // Requires integration with a template engine like html/template.
+ // If not set, Context.Render() returns ErrRendererNotRegistered.
+ Renderer Renderer
+
+ // JSONSerializer handles JSON encoding and decoding for HTTP requests/responses.
+ // Can be replaced with faster alternatives like jsoniter or sonic.
+ // If not set, DefaultJSONSerializer using encoding/json is used.
+ JSONSerializer JSONSerializer
+
+ // IPExtractor defines the strategy for extracting the real client IP address
+ // from requests, particularly important when behind proxies or load balancers.
+ // Used for rate limiting, access control, and logging.
+ // If not set, falls back to checking X-Forwarded-For and X-Real-IP headers.
+ IPExtractor IPExtractor
+
+ // FormParseMaxMemory is default value for memory limit that is used
+ // when parsing multipart forms (See (*http.Request).ParseMultipartForm)
+ FormParseMaxMemory int64
+
+ // EnablePathUnescapingStaticFiles enables path parameter (param: *) unescaping for static file methods.
+ // Default false (safe): encoded slashes (%2f) in the wildcard param are NOT decoded,
+ // preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/* route guard by
+ // not matching that route but having its wildcard param decoded to admin/private.txt.
+ // Set to true only when serving files whose names contain URL-encoded characters
+ // (e.g. "hello world.txt" via /hello%20world.txt) and you are not relying on
+ // route-based ACL guards to restrict access.
+ // If you are enabling this option, make sure you understand the security implications.
+ // See: https://github.com/labstack/echo/security/advisories/GHSA-vfp3-v2gw-7wfq
+ //
+ // Enabling RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when
+ // using different Routes to exclude some of the files from being served.
+ // e.g. if you serve files from directory as such and use different route to exclude some of the files from being served.
+ // 0. given folder structure:
+ // public/
+ // public/index.html
+ // public/admin/private.txt
+ // 1. share `public/` folder contents from the server root with `e.Static("/", "public")`
+ // 2. naively assume that everything under /admin folder is now forbidden
+ // e.GET("/admin/*", func(c *Context) error { return echo.ErrForbidden })
+ // Then request to `/assets/../admin%2fprivate.txt` will be served as router does not match it to guarded route.
+ //
+ // Applies to methods: Echo.Static, Echo.StaticFS, Group.Static, Group.StaticFS.
+ EnablePathUnescapingStaticFiles bool
+
+ // NoGroupAutoRegister404Routes bool is a flag that indicates whether echo.Group should NOT register 404 routes automatically
+ // when there are middlewares registered with the group.
+ // Note: if you decide not to register 404 routes automatically, make sure to check if all your middlewares are executed
+ // as expected. For example - CORS middleware.
+ NoGroupAutoRegister404Routes bool
+}Logger *slog.Logger Logger is the slog logger instance used for application-wide structured logging. +If not set, a default TextHandler writing to stdout is created.
HTTPErrorHandler HTTPErrorHandler HTTPErrorHandler is the centralized error handler that processes errors returned +by handlers and middleware, converting them to appropriate HTTP responses. +If not set, DefaultHTTPErrorHandler(false) is used.
Router Router Router is the HTTP request router responsible for matching URLs to handlers +using a radix tree-based algorithm. +If not set, NewRouter(RouterConfig{}) is used.
OnAddRoute func(route Route) error OnAddRoute is an optional callback hook executed when routes are registered. +Useful for route validation, logging, or custom route processing. +If not set, no callback is executed.
Filesystem fs.FS Filesystem is the fs.FS implementation used for serving static files. +Supports os.DirFS, embed.FS, and custom implementations. +If not set, defaults to current working directory.
Binder Binder Binder handles automatic data binding from HTTP requests to Go structs. +Supports JSON, XML, form data, query parameters, and path parameters. +If not set, DefaultBinder is used.
Validator Validator Validator provides optional struct validation after data binding. +Commonly used with third-party validation libraries. +If not set, Context.Validate() returns ErrValidatorNotRegistered.
Renderer Renderer Renderer provides template rendering for generating HTML responses. +Requires integration with a template engine like html/template. +If not set, Context.Render() returns ErrRendererNotRegistered.
JSONSerializer JSONSerializer JSONSerializer handles JSON encoding and decoding for HTTP requests/responses. +Can be replaced with faster alternatives like jsoniter or sonic. +If not set, DefaultJSONSerializer using encoding/json is used.
IPExtractor IPExtractor IPExtractor defines the strategy for extracting the real client IP address +from requests, particularly important when behind proxies or load balancers. +Used for rate limiting, access control, and logging. +If not set, falls back to checking X-Forwarded-For and X-Real-IP headers.
FormParseMaxMemory int64 FormParseMaxMemory is default value for memory limit that is used +when parsing multipart forms (See (*http.Request).ParseMultipartForm)
EnablePathUnescapingStaticFiles bool EnablePathUnescapingStaticFiles enables path parameter (param: ) unescaping for static file methods. +Default false (safe): encoded slashes (%2f) in the wildcard param are NOT decoded, +preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/ route guard by +not matching that route but having its wildcard param decoded to admin/private.txt. +Set to true only when serving files whose names contain URL-encoded characters +(e.g. "hello world.txt" via /hello%20world.txt) and you are not relying on +route-based ACL guards to restrict access. +If you are enabling this option, make sure you understand the security implications. +See: https://github.com/labstack/echo/security/advisories/GHSA-vfp3-v2gw-7wfq
+Enabling RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when +using different Routes to exclude some of the files from being served. +e.g. if you serve files from directory as such and use different route to exclude some of the files from being served. +0. given folder structure: + public/ + public/index.html + public/admin/private.txt
+public/ folder contents from the server root with e.Static("/", "public")/assets/../admin%2fprivate.txt will be served as router does not match it to guarded route.Applies to methods: Echo.Static, Echo.StaticFS, Group.Static, Group.StaticFS.
NoGroupAutoRegister404Routes bool NoGroupAutoRegister404Routes bool is a flag that indicates whether echo.Group should NOT register 404 routes automatically +when there are middlewares registered with the group. +Note: if you decide not to register 404 routes automatically, make sure to check if all your middlewares are executed +as expected. For example - CORS middleware.
Context represents the context of the current HTTP request. It holds request and +response objects, path, path parameters, data and registered handler.
type Context struct {
+ // contains filtered or unexported fields
+}Attachment sends a response as attachment, prompting client to save the file.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
Bind binds path params, query params and the request body into provided type i. The default binder
+binds body based on Content-Type header.
Blob sends a blob response with status code and content type.
Cookie returns the named cookie provided in the request.
Cookies returns the HTTP cookies sent with the request.
Echo returns the Echo instance.
File sends a response with the content of the file.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
FileFS serves file from given file system.
+When dealing with embed.FS use fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path. This is necessary as //go:embed assets/imagesembeds files with paths includingassets/images` as their prefix.
FormFile returns the multipart form file for the provided name.
FormValue returns the form field value for the provided name.
FormValueOr returns the form field value or default value for the provided name. +Note: FormValueOr does not distinguish if form had no value by that name or value was empty string
FormValues returns the form field values as url.Values.
Get retrieves data from the context. +Method returns any(nil) when key does not exist which is different from typed nil (eg. []byte(nil)).
HTML sends an HTTP response with status code.
HTMLBlob sends an HTTP blob response with status code.
InitializeRoute sets the route related variables of this request to the context.
Inline sends a response as inline, opening the file in the browser.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
IsTLS returns true if HTTP connection is TLS otherwise false.
IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
JSON sends a JSON response with status code.
JSONBlob sends a JSON blob response with status code.
JSONP sends a JSONP response with status code. It uses callback to construct
+the JSONP payload.
JSONPBlob sends a JSONP blob response with status code. It uses callback
+to construct the JSONP payload.
JSONPretty sends a pretty-print JSON with status code.
Logger returns logger in Context
MultipartForm returns the multipart form.
NoContent sends a response with no body and a status code.
Param returns path parameter by name.
ParamOr returns the path parameter or default value for the provided name.
+Notes for DefaultRouter implementation: +Path parameter could be empty for cases like that:
+/release-:version/bin and request URL is /release-/bin/api/:version/image.jpg and request URL is /api//image.jpg
+but not when path parameter is last part of route path/download/file.:ext will not match request /download/file.Path returns the registered path for the handler.
PathValues returns path parameter values.
QueryParam returns the query param for the provided name.
QueryParamOr returns the query param or default value for the provided name.
+Note: QueryParamOr does not distinguish if query had no value by that name or value was empty string
+This means URLs /test?search= and /test would both return 1 for c.QueryParamOr("search", "1")
QueryParams returns the query parameters as url.Values.
QueryString returns the URL query string.
RealIP returns the client IP address using the configured extraction strategy.
+If Echo#IPExtractor is set, it is used to resolve the client IP from the incoming request (typically via proxy
+headers such as X-Forwarded-For or X-Real-IP).
+Look into the ip.go file for comments and examples.
See:
+X-Forwarded-For handling with trust checksX-Real-IP handling with trust checksv4 compatibility (spoofable, no trust checks built in)If no extractor is configured, RealIP falls back to the request RemoteAddr, returning only the host portion.
+Notes:
+Redirect redirects the request to a provided URL with status code.
Render renders a template with data and sends a text/html response with status
+code. Renderer must be registered using Echo.Renderer.
Request returns *http.Request.
Reset resets the context after request completes. It must be called along
+with Echo#AcquireContext() and Echo#ReleaseContext().
+See Echo#ServeHTTP()
Response returns *Response.
RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route.
+RouteInfo returns generic "empty" struct for these cases:
+e.Pre())Scheme returns the HTTP protocol scheme, http or https.
Set saves data in the context.
SetCookie adds a Set-Cookie header in HTTP response.
SetLogger sets logger in Context
SetPath sets the registered path for the handler.
SetPathValues sets path parameters for current request.
SetRequest sets *http.Request.
SetResponse sets *http.ResponseWriter. Some context methods and/or middleware require that given ResponseWriter implements following
+method Unwrap() http.ResponseWriter which eventually should return *echo.Response instance.
Stream sends a streaming response with status code and content type.
String sends a string response with status code.
Validate validates provided i. It is usually called after Context#Bind().
+Validator must be registered using Echo#Validator.
XML sends an XML response with status code.
XMLBlob sends an XML blob response with status code.
XMLPretty sends a pretty-print XML with status code.
DefaultBinder is the default implementation of the Binder interface.
type DefaultBinder struct{}Bind implements the Binder#Bind function.
+Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous
+step bound values. For single source binding use their own methods BindBody, BindQueryParams, BindPathValues.
DefaultJSONSerializer implements JSON encoding using encoding/json.
type DefaultJSONSerializer struct{}Deserialize reads a JSON from a request body and converts it into an interface.
+The body is read into a pooled buffer and decoded with json.Unmarshal rather +than streaming through json.NewDecoder. This avoids allocating a decoder and +its internal read buffer on every request. json.Unmarshal does not retain a +reference to the input slice, so the buffer is safe to reuse afterwards.
+Note: the full request body is read into memory before decoding. As with any +JSON parser, decoding untrusted input can allocate large amounts of memory; +guard such endpoints with middleware.BodyLimit (or http.MaxBytesReader), +which makes the body read here fail fast once the limit is exceeded.
Serialize converts an interface into a json and writes it to the response. +You can optionally use the indent parameter to produce pretty JSONs.
DefaultRouter is the registry of all registered routes for an Echo instance for
+request matching and URL path parameter parsing.
+Note: DefaultRouter is not coroutine-safe. Do not Add/Remove routes after HTTP server has been started with Echo.
type DefaultRouter struct {
+ // contains filtered or unexported fields
+}Add registers a new route for method and path with matching handler.
Remove unregisters registered route
Route looks up a handler registered for method and path. It also parses URL for path parameters and loads them +into context.
+For performance:
+Echo#AcquireContext()Context#Reset()Echo#ReleaseContext().Routes returns all registered routes
Echo is the top-level framework instance.
+Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these +fields from handlers/middlewares and changing field values at the same time leads to data-races. +Same rule applies to adding new routes after server has been started - Adding a route is not Goroutine safe action.
type Echo struct {
+ Binder Binder
+
+ // Filesystem is the file system used for serving static files. Defaults to the current working directory (os.Getwd()).
+ //
+ // Note: fs.FS.Open() already assumes that file names are relative to FS root path and considers name with prefix `/` as invalid
+ // so if you have `fs := os.DirFS("/tmp")` and you try to `fs.Open("/tmp/file.txt")` it will fail, but "file.txt"
+ // would succeed. `echo.NewDefaultFS("/tmp")` overwrites this behavior and allows you to use Open with a matching
+ // absolute path prefix.
+ Filesystem fs.FS
+
+ Renderer Renderer
+ Validator Validator
+ JSONSerializer JSONSerializer
+ IPExtractor IPExtractor
+ OnAddRoute func(route Route) error
+ HTTPErrorHandler HTTPErrorHandler
+ Logger *slog.Logger
+ // contains filtered or unexported fields
+}Binder Binder Filesystem fs.FS Filesystem is the file system used for serving static files. Defaults to the current working directory (os.Getwd()).
+Note: fs.FS.Open() already assumes that file names are relative to FS root path and considers name with prefix / as invalid
+so if you have fs := os.DirFS("/tmp") and you try to fs.Open("/tmp/file.txt") it will fail, but "file.txt"
+would succeed. echo.NewDefaultFS("/tmp") overwrites this behavior and allows you to use Open with a matching
+absolute path prefix.
Renderer Renderer Validator Validator JSONSerializer JSONSerializer IPExtractor IPExtractor OnAddRoute func(route Route) error HTTPErrorHandler HTTPErrorHandler Logger *slog.Logger AcquireContext returns an empty Context instance from the pool.
+You must return the context by calling ReleaseContext().
Add registers a new route for an HTTP method and path with matching handler +in the router with optional route-level middleware.
AddRoute registers a new Route with default host Router
Any registers a new route for all HTTP methods (supported by Echo) and path with matching handler +in the router with optional route-level middleware.
+Note: this method only adds specific set of supported HTTP methods as handler and is not true +"catch-any-arbitrary-method" way of matching requests.
CONNECT registers a new CONNECT route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
DELETE registers a new DELETE route for a path with matching handler in the router +with optional route-level middleware. Panics on error.
File registers a new route with path to serve a static file with optional route-level middleware. Panics on error.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
FileFS registers a new route with path to serve file from the provided file system.
+Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
GET registers a new GET route for a path with matching handler in the router +with optional route-level middleware. Panics on error.
Group creates a new router group with prefix and optional group-level middleware.
HEAD registers a new HEAD route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
Match registers a new route for multiple HTTP methods and path with matching +handler in the router with optional route-level middleware. Panics on error.
Middlewares returns registered route level middlewares. Does not contain any group level +middlewares. Use this method to build your own ServeHTTP method.
+NOTE: returned slice is not a copy. Do not mutate.
NewContext returns a new Context instance.
+Note: both request and response can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway +these arguments are useful when creating context for tests and cases like that.
OPTIONS registers a new OPTIONS route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
PATCH registers a new PATCH route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
POST registers a new POST route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
PUT registers a new PUT route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
Pre adds middleware to the chain which is run before router tries to find matching route. +Meaning middleware is executed even for 404 (not found) cases.
PreMiddlewares returns registered pre middlewares. These are middleware to the chain +which are run before router tries to find matching route. +Use this method to build your own ServeHTTP method.
+NOTE: returned slice is not a copy. Do not mutate.
QUERY registers a new QUERY route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
ReleaseContext returns the Context instance back to the pool.
+You must call it after AcquireContext().
RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases)
+for current request URL.
+Path supports static and named/any parameters just like other http method is defined. Generally path is ended with
+wildcard/match-any character (/*, /download/* etc).
Example: e.RouteNotFound("/*", func(c *echo.Context) error { return c.NoContent(http.StatusNotFound) })
Router returns the default router.
ServeHTTP implements http.Handler interface, which serves HTTP requests.
Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by
+sending os.Interrupt signal with ctrl+c. Method returns only errors that are not http.ErrServerClosed.
Note: this method is created for use in examples/demos and is deliberately simple without providing configuration +options.
+In need of customization use:
+ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+defer cancel()
+sc := echo.StartConfig{Address: ":8080"}
+if err := sc.Start(ctx, e); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ slog.Error(err.Error())
+}// or standard library http.Server
s := http.Server{Addr: ":8080", Handler: e}
+if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ slog.Error(err.Error())
+}Static registers a new route with path prefix to serve static files from the provided root directory.
StaticFS registers a new route with path prefix to serve static files from the provided file system.
+When dealing with embed.FS use fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path. This is necessary as //go:embed assets/imagesembeds files with paths includingassets/images` as their prefix.
TRACE registers a new TRACE route for a path with matching handler in the +router with optional route-level middleware. Panics on error.
Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed.
Group is a set of sub-routes for a specified route. It can be used for inner +routes that share a common middleware or functionality that should be separate +from the parent echo instance while still inheriting from it.
type Group struct {
+ // contains filtered or unexported fields
+}Add implements Echo#Add() for sub-routes within the Group. Panics on error.
AddRoute registers a new Routable with Router
Any implements Echo#Any() for sub-routes within the Group. Panics on error.
CONNECT implements Echo#CONNECT() for sub-routes within the Group. Panics on error.
DELETE implements Echo#DELETE() for sub-routes within the Group. Panics on error.
File implements Echo#File() for sub-routes within the Group. Panics on error.
Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
FileFS implements Echo#FileFS() for sub-routes within the Group.
Avoid using the leading / slash as most of the Go standard library fs.FS implementations require relative paths for
+file operations.
GET implements Echo#GET() for sub-routes within the Group. Panics on error.
Group creates a new sub-group with prefix and optional sub-group-level middleware.
+Important! Group middlewares are executed in case there was no exact route match as by default Group registers
+/* NotFound routes for itself. If this kind of behavior is not needed, then create an Echo instance with the noAutoRegisterRoutes
+flag set to true. Example echo.NewWithConfig(echo.Config{NoGroupAutoRegister404Routes: true}).
HEAD implements Echo#HEAD() for sub-routes within the Group. Panics on error.
Match implements Echo#Match() for sub-routes within the Group. Panics on error.
OPTIONS implements Echo#OPTIONS() for sub-routes within the Group. Panics on error.
PATCH implements Echo#PATCH() for sub-routes within the Group. Panics on error.
POST implements Echo#POST() for sub-routes within the Group. Panics on error.
PUT implements Echo#PUT() for sub-routes within the Group. Panics on error.
QUERY implements Echo#QUERY() for sub-routes within the Group. Panics on error.
RouteNotFound implements Echo#RouteNotFound() for sub-routes within the Group.
Example: g.RouteNotFound("/*", func(c *echo.Context) error { return c.NoContent(http.StatusNotFound) })
Static implements Echo#Static() for sub-routes within the Group.
StaticFS implements Echo#StaticFS() for sub-routes within the Group.
When dealing with embed.FS use fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path. This is necessary as //go:embed assets/imagesembeds files with paths includingassets/images` as their prefix.
TRACE implements Echo#TRACE() for sub-routes within the Group. Panics on error.
Use implements Echo#Use() for sub-routes within the Group.
Important! Group middlewares are executed in case there was no exact route match as by default Group registers
+/* NotFound routes for itself. If this kind of behavior is not needed, then create an Echo instance with the noAutoRegisterRoutes
+flag set to true. Example echo.NewWithConfig(echo.Config{NoGroupAutoRegister404Routes: true}).
HTTPError represents an error that occurred while handling a request.
type HTTPError struct {
+ // Code is status code for HTTP response
+ Code int `json:"-"`
+ Message string `json:"message"`
+ // contains filtered or unexported fields
+}Code int `json:"-"`Code is status code for HTTP response
Message string `json:"message"`Error makes it compatible with the error interface.
StatusCode returns status code for HTTP response
Wrap returns a new HTTPError with given errors wrapped inside
HTTPErrorHandler is a centralized HTTP error handler.
type HTTPErrorHandler func(c *Context, err error)HTTPStatusCoder is an interface that errors can implement to produce status code for HTTP response
type HTTPStatusCoder interface {
+ StatusCode() int
+}StatusCode func() int HandlerFunc defines a function to serve HTTP requests.
type HandlerFunc func(c *Context) errorIPExtractor is a function to extract IP addr from http.Request. +Set appropriate one to Echo#IPExtractor. +See https://echo.labstack.com/guide/ip-address for more details.
type IPExtractor func(*http.Request) stringJSONSerializer is the interface that encodes and decodes JSON to and from interfaces.
type JSONSerializer interface {
+ Serialize(c *Context, target any, indent string) error
+ Deserialize(c *Context, target any) error
+}Serialize func(c *Context, target any, indent string) error Deserialize func(c *Context, target any) error MiddlewareConfigurator defines interface for creating middleware handlers with possibility to return configuration errors instead of panicking.
type MiddlewareConfigurator interface {
+ ToMiddleware() (MiddlewareFunc, error)
+}ToMiddleware func() (MiddlewareFunc, error) MiddlewareFunc defines a function to process middleware.
type MiddlewareFunc func(next HandlerFunc) HandlerFuncPathValue is tuple pf path parameter name and its value in request path
type PathValue struct {
+ Name string
+ Value string
+}Name string Value string PathValues is collections of PathValue instances with various helper methods
type PathValues []PathValueGet returns path parameter value for given name or false.
GetOr returns path parameter value for given name or default value if the name does not exist.
Renderer is the interface that wraps the Render function.
type Renderer interface {
+ Render(c *Context, w io.Writer, templateName string, data any) error
+}Render func(c *Context, w io.Writer, templateName string, data any) error Response wraps an http.ResponseWriter and implements its interface to be used +by an HTTP handler to construct an HTTP response. +See: https://golang.org/pkg/net/http/#ResponseWriter
type Response struct {
+ http.ResponseWriter
+
+ Status int
+ Size int64
+ Committed bool
+ // contains filtered or unexported fields
+}http.ResponseWriter Status int Size int64 Committed bool After registers a function which is called just after the response is written.
Before registers a function which is called just before the response (status) is written.
Flush implements the http.Flusher interface to allow an HTTP handler to flush +buffered data to the client. +See http.Flusher
Hijack implements the http.Hijacker interface to allow an HTTP handler to +take over the connection. +This method is relevant to Websocket connection upgrades, proxis, and other advanced use cases. +See http.Hijacker
Unwrap returns the original http.ResponseWriter. +ResponseController can be used to access the original http.ResponseWriter. +See [https://go.dev/blog/go1.20]
Write writes the data to the connection as part of an HTTP reply.
WriteHeader sends an HTTP response header with status code. If WriteHeader is +not called explicitly, the first call to Write will trigger an implicit +WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly +used to send error codes.
Route contains information to adding/registering new route with the router. +Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path fields.
type Route struct {
+ Method string
+ Path string
+ Name string
+
+ // HandlerFunc is a function that handles HTTP requests. This could be left nil when the Router implementation allows
+ // fallback to default/global handlers in certain situations.
+ Handler HandlerFunc
+ Middlewares []MiddlewareFunc
+}Method string Path string Name string Handler HandlerFunc HandlerFunc is a function that handles HTTP requests. This could be left nil when the Router implementation allows +fallback to default/global handlers in certain situations.
Middlewares []MiddlewareFunc ToRouteInfo converts Route to RouteInfo
WithPrefix recreates Route with added group prefix and group middlewares it is grouped to.
RouteInfo contains information about registered Route.
type RouteInfo struct {
+ Name string
+ Method string
+ Path string
+ Parameters []string
+}Name string Method string Path string Parameters []string Clone creates copy of RouteInfo
Reverse reverses route to URL string by replacing path parameters with given params values.
Router is interface for routing request contexts to registered routes.
+Contract between Echo/Context instance and the router:
+Echo.contextPathParamAllocSize).type Router interface {
+ // Add registers Routable with the Router and returns registered RouteInfo.
+ //
+ // Router may change Route.Path value in returned RouteInfo.Path.
+ // Router generates RouteInfo.Parameters values from Route.Path.
+ // Router generates RouteInfo.Name value if it is not provided.
+ Add(routable Route) (RouteInfo, error)
+
+ // Remove removes route from the Router.
+ //
+ // Router may choose not to implement this method.
+ Remove(method string, path string) error
+
+ // Routes returns information about all registered routes
+ Routes() Routes
+
+ // Route searches Router for matching route and applies it to the given context. In case when no matching method
+ // was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404
+ // handler function.
+ //
+ // Router must populate Context during Router.Route call with:
+ // - Context.InitializeRoute() (IMPORTANT! to reduce allocations use same slice that c.PathValues() returns)
+ // - optionally can set additional information to Context with Context.Set()
+ Route(c *Context) HandlerFunc
+}Add func(routable Route) (RouteInfo, error) Add registers Routable with the Router and returns registered RouteInfo.
+Router may change Route.Path value in returned RouteInfo.Path. +Router generates RouteInfo.Parameters values from Route.Path. +Router generates RouteInfo.Name value if it is not provided.
Remove func(method string, path string) error Remove removes route from the Router.
+Router may choose not to implement this method.
Routes func() Routes Routes returns information about all registered routes
Route func(c *Context) HandlerFunc Route searches Router for matching route and applies it to the given context. In case when no matching method +was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 +handler function.
+Router must populate Context during Router.Route call with:
+RouterConfig is configuration options for (default) router
type RouterConfig struct {
+ // NotFoundHandler is a handler that is executed when no route matches the request.
+ NotFoundHandler HandlerFunc
+
+ // MethodNotAllowedHandler is a handler that is executed when no route with exact METHOD matches the request but
+ // there is a route with same path but different method.
+ MethodNotAllowedHandler HandlerFunc
+
+ // OptionsMethodHandler is a handler that is executed when an OPTIONS request is made.
+ OptionsMethodHandler HandlerFunc
+
+ // AllowOverwritingRoute allows overwriting existing routes. If false, then adding a route with the same method
+ // and path will return an error.
+ AllowOverwritingRoute bool
+
+ // UnescapePathParamValues forces router to unescape path parameter values before setting them in context.
+ UnescapePathParamValues bool
+
+ // UseEscapedPathForMatching forces router to use an escaped path (req.URL.RawPath instead of req.URL.Path) for matching.
+ // Difference between URL.RawPath and URL.Path is:
+ // * URL.Path is where request path is stored. Value is stored in decoded form: /%47%6f%2f becomes /Go/.
+ // * URL.RawPath is an optional field which only gets set if the default encoding is different from Path.
+ UseEscapedPathForMatching bool
+
+ // AutoHandleHEAD enables automatic handling of HTTP HEAD requests by
+ // falling back to the corresponding GET route.
+ //
+ // When enabled, a HEAD request will match the same handler as GET for
+ // the route, but the response body is suppressed in accordance with
+ // HTTP semantics. Headers (e.g., Content-Length, Content-Type) are
+ // preserved as if a GET request was made.
+ //
+ // Security considerations: the GET handler is fully executed for every
+ // HEAD request, including all side effects:
+ // - State-mutating operations (DB writes, audit logs, counters) run.
+ // - Rate-limiting middleware consumes quota, enabling low-cost exhaustion.
+ // - Expensive computations run with no response body returned to the
+ // caller, making HEAD cheaper to abuse for DoS than GET.
+ // - All GET routes become enumerable via HEAD probing (200 = route
+ // exists, 405 = route absent).
+ //
+ // If route confidentiality/state-mutation is a concern, leave AutoHandleHEAD disabled
+ // and register explicit HEAD handlers only for routes that are safe to
+ // expose (e.g. e.HEAD("/public", handler)).
+ // You can leverage Echo.OnAddRoute callback to add HEAD routes explicitly from a single place.
+ //
+ // Disabled by default.
+ AutoHandleHEAD bool
+}NotFoundHandler HandlerFunc NotFoundHandler is a handler that is executed when no route matches the request.
MethodNotAllowedHandler HandlerFunc MethodNotAllowedHandler is a handler that is executed when no route with exact METHOD matches the request but +there is a route with same path but different method.
OptionsMethodHandler HandlerFunc OptionsMethodHandler is a handler that is executed when an OPTIONS request is made.
AllowOverwritingRoute bool AllowOverwritingRoute allows overwriting existing routes. If false, then adding a route with the same method +and path will return an error.
UnescapePathParamValues bool UnescapePathParamValues forces router to unescape path parameter values before setting them in context.
UseEscapedPathForMatching bool UseEscapedPathForMatching forces router to use an escaped path (req.URL.RawPath instead of req.URL.Path) for matching. +Difference between URL.RawPath and URL.Path is:
+AutoHandleHEAD bool AutoHandleHEAD enables automatic handling of HTTP HEAD requests by +falling back to the corresponding GET route.
+When enabled, a HEAD request will match the same handler as GET for +the route, but the response body is suppressed in accordance with +HTTP semantics. Headers (e.g., Content-Length, Content-Type) are +preserved as if a GET request was made.
+Security considerations: the GET handler is fully executed for every +HEAD request, including all side effects:
+If route confidentiality/state-mutation is a concern, leave AutoHandleHEAD disabled +and register explicit HEAD handlers only for routes that are safe to +expose (e.g. e.HEAD("/public", handler)). +You can leverage Echo.OnAddRoute callback to add HEAD routes explicitly from a single place.
+Disabled by default.
Routes is collection of RouteInfo instances with various helper methods.
type Routes []RouteInfoClone creates copy of Routes
FilterByMethod searched for matching route info by method
FilterByName searched for matching route info by name
FilterByPath searched for matching route info by path
FindByMethodPath searched for matching route info by method and path
Reverse reverses route to URL string by replacing path parameters with given params values.
StartConfig is for creating configured http.Server instance to start serve http(s) requests with given Echo instance
type StartConfig struct {
+ // Address specifies the address where listener will start listening on to serve HTTP(s) requests
+ Address string
+
+ // HideBanner instructs Start* method not to print banner when starting the Server.
+ HideBanner bool
+ // HidePort instructs Start* method not to print port when starting the Server.
+ HidePort bool
+
+ // CertFilesystem is filesystem is used to read `certFile` and `keyFile` when StartTLS method is called.
+ CertFilesystem fs.FS
+
+ // TLSConfig is used to configure TLS. If Listener is set, TLSConfig is not used to create the listener.
+ TLSConfig *tls.Config
+
+ // Listener is used to start server with the custom listener.
+ Listener net.Listener
+ // ListenerNetwork is used configure on which Network listener will use.
+ // If Listener is set, ListenerNetwork is not used.
+ ListenerNetwork string
+ // ListenerAddrFunc will be called after listener is created and started to listen for connections. This is useful in
+ // testing situations when server is started on random port `address = ":0"` in that case you can get actual port where
+ // listener is listening on.
+ ListenerAddrFunc func(addr net.Addr)
+
+ // GracefulTimeout is timeout value (defaults to 10sec) graceful shutdown will wait for server to handle ongoing requests
+ // before shutting down the server.
+ GracefulTimeout time.Duration
+ // OnShutdownError is called when graceful shutdown results an error. for example when listeners are not shut down within
+ // given timeout
+ OnShutdownError func(err error)
+
+ // BeforeServeFunc is callback that is called just before server starts to serve HTTP request.
+ // Use this callback when you want to configure http.Server different timeouts/limits/etc
+ BeforeServeFunc func(s *http.Server) error
+}Address string Address specifies the address where listener will start listening on to serve HTTP(s) requests
HideBanner bool HideBanner instructs Start* method not to print banner when starting the Server.
HidePort bool HidePort instructs Start* method not to print port when starting the Server.
CertFilesystem fs.FS CertFilesystem is filesystem is used to read certFile and keyFile when StartTLS method is called.
TLSConfig *tls.Config TLSConfig is used to configure TLS. If Listener is set, TLSConfig is not used to create the listener.
Listener net.Listener Listener is used to start server with the custom listener.
ListenerNetwork string ListenerNetwork is used configure on which Network listener will use. +If Listener is set, ListenerNetwork is not used.
ListenerAddrFunc func(addr net.Addr) ListenerAddrFunc will be called after listener is created and started to listen for connections. This is useful in
+testing situations when server is started on random port address = ":0" in that case you can get actual port where
+listener is listening on.
GracefulTimeout time.Duration GracefulTimeout is timeout value (defaults to 10sec) graceful shutdown will wait for server to handle ongoing requests +before shutting down the server.
OnShutdownError func(err error) OnShutdownError is called when graceful shutdown results an error. for example when listeners are not shut down within +given timeout
BeforeServeFunc func(s *http.Server) error BeforeServeFunc is callback that is called just before server starts to serve HTTP request. +Use this callback when you want to configure http.Server different timeouts/limits/etc
Start starts given Handler with HTTP(s) server.
StartTLS starts given Handler with HTTPS server.
+If certFile or keyFile is string the values are treated as file paths.
+If certFile or keyFile is []byte the values are treated as the certificate or key as-is.
TemplateRenderer is helper to ease creating renderers for html/template and text/template packages.
+Example usage:
e.Renderer = &echo.TemplateRenderer{
+ Template: template.Must(template.ParseGlob("templates/*.html")),
+ }
+
+ e.Renderer = &echo.TemplateRenderer{
+ Template: template.Must(template.New("hello").Parse("Hello, {{.}}!")),
+ }type TemplateRenderer struct {
+ Template interface {
+ ExecuteTemplate(wr io.Writer, name string, data any) error
+ }
+}Template interface {
+ ExecuteTemplate(wr io.Writer, name string, data any) error
+} Render renders the template with given data.
TimeLayout specifies the format for parsing time values in request parameters. +It can be a standard Go time layout string or one of the special Unix time layouts.
type TimeLayout stringTimeOpts is options for parsing time.Time values
type TimeOpts struct {
+ // Layout specifies the format for parsing time values in request parameters.
+ // It can be a standard Go time layout string or one of the special Unix time layouts.
+ //
+ // Parsing layout defaults to: echo.TimeLayout(time.RFC3339Nano)
+ // - To convert to custom layout use `echo.TimeLayout("2006-01-02")`
+ // - To convert unix timestamp (integer) to time.Time use `echo.TimeLayoutUnixTime`
+ // - To convert unix timestamp in milliseconds to time.Time use `echo.TimeLayoutUnixTimeMilli`
+ // - To convert unix timestamp in nanoseconds to time.Time use `echo.TimeLayoutUnixTimeNano`
+ Layout TimeLayout
+
+ // ParseInLocation is location used with time.ParseInLocation for layout that do not contain
+ // timezone information to set output time in given location.
+ // Defaults to time.UTC
+ ParseInLocation *time.Location
+
+ // ToInLocation is location to which parsed time is converted to after parsing.
+ // The parsed time will be converted using time.In(ToInLocation).
+ // Defaults to time.UTC
+ ToInLocation *time.Location
+}Layout TimeLayout Layout specifies the format for parsing time values in request parameters. +It can be a standard Go time layout string or one of the special Unix time layouts.
+Parsing layout defaults to: echo.TimeLayout(time.RFC3339Nano)
+echo.TimeLayout("2006-01-02")echo.TimeLayoutUnixTimeecho.TimeLayoutUnixTimeMilliecho.TimeLayoutUnixTimeNanoParseInLocation *time.Location ParseInLocation is location used with time.ParseInLocation for layout that do not contain +timezone information to set output time in given location. +Defaults to time.UTC
ToInLocation *time.Location ToInLocation is location to which parsed time is converted to after parsing. +The parsed time will be converted using time.In(ToInLocation). +Defaults to time.UTC
TrustOption is config for which IP address to trust
type TrustOption func(*ipChecker)Validator is the interface that wraps the Validate function.
type Validator interface {
+ Validate(i any) error
+}Validate func(i any) error ValueBinder provides utility methods for binding query or path parameter to various Go built-in types
type ValueBinder struct {
+ // ValueFunc is used to get single parameter (first) value from request
+ ValueFunc func(sourceParam string) string
+ // ValuesFunc is used to get all values for parameter from request. i.e. `/api/search?ids=1&ids=2`
+ ValuesFunc func(sourceParam string) []string
+ // ErrorFunc is used to create errors. Allows you to use your own error type, that for example marshals to your specific json response
+ ErrorFunc func(sourceParam string, values []string, message string, internalError error) error
+ // contains filtered or unexported fields
+}ValueFunc func(sourceParam string) string ValueFunc is used to get single parameter (first) value from request
ValuesFunc func(sourceParam string) []string ValuesFunc is used to get all values for parameter from request. i.e. /api/search?ids=1&ids=2
ErrorFunc func(sourceParam string, values []string, message string, internalError error) error ErrorFunc is used to create errors. Allows you to use your own error type, that for example marshals to your specific json response
BindError returns first seen bind error and resets/empties binder errors for further calls
{
+
+ failFastRouteFunc := func(c *echo.Context) error {
+ var opts struct {
+ IDs []int64
+ Active bool
+ }
+ length := int64(50)
+
+ b := echo.QueryParamsBinder(c)
+
+ err := b.Int64("length", &length).
+ Int64s("ids", &opts.IDs).
+ Bool("active", &opts.Active).
+ BindError()
+ if err != nil {
+ bErr := err.(*echo.BindingError)
+ return fmt.Errorf("my own custom error for field: %s values: %v", bErr.Field, bErr.Values)
+ }
+ fmt.Printf("active = %v, length = %v, ids = %v\n", opts.Active, length, opts.IDs)
+
+ return c.JSON(http.StatusOK, opts)
+ }
+
+ e := echo.New()
+ c := e.NewContext(
+ httptest.NewRequest(http.MethodGet, "/api/endpoint?active=true&length=25&ids=1&ids=2&ids=3", nil),
+ httptest.NewRecorder(),
+ )
+
+ _ = failFastRouteFunc(c)
+
+}Output:
+active = true, length = 25, ids = [1 2 3]BindErrors returns all bind errors and resets/empties binder errors for further calls
{
+
+ routeFunc := func(c *echo.Context) error {
+ var opts struct {
+ IDs []int64
+ Active bool
+ }
+ length := int64(50)
+
+ b := echo.QueryParamsBinder(c)
+
+ errs := b.Int64("length", &length).
+ Int64s("ids", &opts.IDs).
+ Bool("active", &opts.Active).
+ BindErrors()
+ if errs != nil {
+ for _, err := range errs {
+ bErr := err.(*echo.BindingError)
+ log.Printf("in case you want to access what field: %s values: %v failed", bErr.Field, bErr.Values)
+ }
+ return fmt.Errorf("%v fields failed to bind", len(errs))
+ }
+ fmt.Printf("active = %v, length = %v, ids = %v", opts.Active, length, opts.IDs)
+
+ return c.JSON(http.StatusOK, opts)
+ }
+
+ e := echo.New()
+ c := e.NewContext(
+ httptest.NewRequest(http.MethodGet, "/api/endpoint?active=true&length=25&ids=1&ids=2&ids=3", nil),
+ httptest.NewRecorder(),
+ )
+
+ _ = routeFunc(c)
+
+}Output:
+active = true, length = 25, ids = [1 2 3]BindUnmarshaler binds parameter to destination implementing BindUnmarshaler interface
BindWithDelimiter binds parameter to destination by suitable conversion function. +Delimiter is used before conversion to split parameter value to separate values
Bool binds parameter to bool variable
Bools binds parameter values to slice of bool variables
Byte binds parameter to byte variable
CustomFunc binds parameter values with Func. Func is called only when parameter values exist.
{
+
+ routeFunc := func(c *echo.Context) error {
+ length := int64(50)
+ var binary []byte
+
+ b := echo.QueryParamsBinder(c)
+ errs := b.Int64("length", &length).
+ CustomFunc("base64", func(values []string) []error {
+ if len(values) == 0 {
+ return nil
+ }
+ decoded, err := base64.URLEncoding.DecodeString(values[0])
+ if err != nil {
+
+ return []error{echo.NewBindingError("base64", values[0:1], "failed to decode base64", err)}
+ }
+ binary = decoded
+ return nil
+ }).
+ BindErrors()
+
+ if errs != nil {
+ for _, err := range errs {
+ bErr := err.(*echo.BindingError)
+ log.Printf("in case you want to access what field: %s values: %v failed", bErr.Field, bErr.Values)
+ }
+ return fmt.Errorf("%v fields failed to bind", len(errs))
+ }
+ fmt.Printf("length = %v, base64 = %s", length, binary)
+
+ return c.JSON(http.StatusOK, "ok")
+ }
+
+ e := echo.New()
+ c := e.NewContext(
+ httptest.NewRequest(http.MethodGet, "/api/endpoint?length=25&base64=SGVsbG8gV29ybGQ%3D", nil),
+ httptest.NewRecorder(),
+ )
+ _ = routeFunc(c)
+
+}Output:
+length = 25, base64 = Hello WorldDuration binds parameter to time.Duration variable
Durations binds parameter values to slice of time.Duration variables
FailFast set internal flag to indicate if binding methods will return early (without binding) when previous bind failed +NB: call this method before any other binding methods as it modifies binding methods behaviour
Float32 binds parameter to float32 variable
Float32s binds parameter values to slice of float32 variables
Float64 binds parameter to float64 variable
Float64s binds parameter values to slice of float64 variables
Int binds parameter to int variable
Int16 binds parameter to int16 variable
Int16s binds parameter to slice of int16
Int32 binds parameter to int32 variable
Int32s binds parameter to slice of int32
Int64 binds parameter to int64 variable
Int64s binds parameter to slice of int64
Int8 binds parameter to int8 variable
Int8s binds parameter to slice of int8
Ints binds parameter to slice of int
JSONUnmarshaler binds parameter to destination implementing json.Unmarshaler interface
MustBindUnmarshaler requires parameter value to exist to bind to destination implementing BindUnmarshaler interface. +Returns error when value does not exist
MustBindWithDelimiter requires parameter value to exist to bind destination by suitable conversion function. +Delimiter is used before conversion to split parameter value to separate values
MustBool requires parameter value to exist to bind to bool variable. Returns error when value does not exist
MustBools requires parameter values to exist to bind to slice of bool variables. Returns error when values does not exist
MustByte requires parameter value to exist to bind to byte variable. Returns error when value does not exist
MustCustomFunc requires parameter values to exist to bind with Func. Returns error when value does not exist.
MustDuration requires parameter value to exist to bind to time.Duration variable. Returns error when value does not exist
MustDurations requires parameter values to exist to bind to slice of time.Duration variables. Returns error when values does not exist
MustFloat32 requires parameter value to exist to bind to float32 variable. Returns error when value does not exist
MustFloat32s requires parameter values to exist to bind to slice of float32 variables. Returns error when values does not exist
MustFloat64 requires parameter value to exist to bind to float64 variable. Returns error when value does not exist
MustFloat64s requires parameter values to exist to bind to slice of float64 variables. Returns error when values does not exist
MustInt requires parameter value to exist to bind to int variable. Returns error when value does not exist
MustInt16 requires parameter value to exist to bind to int16 variable. Returns error when value does not exist
MustInt16s requires parameter value to exist to bind to int16 slice variable. Returns error when value does not exist
MustInt32 requires parameter value to exist to bind to int32 variable. Returns error when value does not exist
MustInt32s requires parameter value to exist to bind to int32 slice variable. Returns error when value does not exist
MustInt64 requires parameter value to exist to bind to int64 variable. Returns error when value does not exist
MustInt64s requires parameter value to exist to bind to int64 slice variable. Returns error when value does not exist
MustInt8 requires parameter value to exist to bind to int8 variable. Returns error when value does not exist
MustInt8s requires parameter value to exist to bind to int8 slice variable. Returns error when value does not exist
MustInts requires parameter value to exist to bind to int slice variable. Returns error when value does not exist
MustJSONUnmarshaler requires parameter value to exist to bind to destination implementing json.Unmarshaler interface. +Returns error when value does not exist
MustString requires parameter value to exist to bind to string variable. Returns error when value does not exist
MustStrings requires parameter values to exist to bind to slice of string variables. Returns error when value does not exist
MustTextUnmarshaler requires parameter value to exist to bind to destination implementing encoding.TextUnmarshaler interface. +Returns error when value does not exist
MustTime requires parameter value to exist to bind to time.Time variable. Returns error when value does not exist
MustTimes requires parameter values to exist to bind to slice of time.Time variables. Returns error when values does not exist
MustUint requires parameter value to exist to bind to uint variable. Returns error when value does not exist
MustUint16 requires parameter value to exist to bind to uint16 variable. Returns error when value does not exist
MustUint16s requires parameter value to exist to bind to uint16 slice variable. Returns error when value does not exist
MustUint32 requires parameter value to exist to bind to uint32 variable. Returns error when value does not exist
MustUint32s requires parameter value to exist to bind to uint32 slice variable. Returns error when value does not exist
MustUint64 requires parameter value to exist to bind to uint64 variable. Returns error when value does not exist
MustUint64s requires parameter value to exist to bind to uint64 slice variable. Returns error when value does not exist
MustUint8 requires parameter value to exist to bind to uint8 variable. Returns error when value does not exist
MustUint8s requires parameter value to exist to bind to uint8 slice variable. Returns error when value does not exist
MustUints requires parameter value to exist to bind to uint slice variable. Returns error when value does not exist
MustUnixTime requires parameter value to exist to bind to time.Time variable (in local time corresponding +to the given Unix time). Returns error when value does not exist.
+Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00
+Note:
+MustUnixTimeMilli requires parameter value to exist to bind to time.Time variable (in local time corresponding +to the given Unix time in millisecond precision). Returns error when value does not exist.
+Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00
+Note:
+MustUnixTimeNano requires parameter value to exist to bind to time.Time variable (in local time corresponding +to the given Unix time value in nanosecond precision). Returns error when value does not exist.
+Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 +Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 +Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00
+Note:
+String binds parameter to string variable
Strings binds parameter values to slice of string
TextUnmarshaler binds parameter to destination implementing encoding.TextUnmarshaler interface
Time binds parameter to time.Time variable
Times binds parameter values to slice of time.Time variables
Uint binds parameter to uint variable
Uint16 binds parameter to uint16 variable
Uint16s binds parameter to slice of uint16
Uint32 binds parameter to uint32 variable
Uint32s binds parameter to slice of uint32
Uint64 binds parameter to uint64 variable
Uint64s binds parameter to slice of uint64
Uint8 binds parameter to uint8 variable
Uint8s binds parameter to slice of uint8
Uints binds parameter to slice of uint
UnixTime binds parameter to time.Time variable (in local Time corresponding to the given Unix time).
+Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00
+Note:
+UnixTimeMilli binds parameter to time.Time variable (in local time corresponding to the given Unix time in millisecond precision).
+Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00
+Note:
+UnixTimeNano binds parameter to time.Time variable (in local time corresponding to the given Unix time in nanosecond precision).
+Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 +Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 +Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00
+Note:
+