Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

echo

v4.16.6
github.com/labstack/echo/v4

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

377 matches

Top ↑

Package echo implements high performance, minimalist Go web framework.

Example:

package main

import (
  "net/http"

  "github.com/labstack/echo/v4"
  "github.com/labstack/echo/v4/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.Logger())
  e.Use(middleware.Recover())

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

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

Learn more at https://echo.labstack.com

Constants

TimeLayoutUnixTime (3 declarations)

const (
	TimeLayoutUnixTime      = TimeLayout("UnixTime")      // Unix timestamp in seconds
	TimeLayoutUnixTimeMilli = TimeLayout("UnixTimeMilli") // Unix timestamp in milliseconds
	TimeLayoutUnixTimeNano  = TimeLayout("UnixTimeNano")  // Unix timestamp in nanoseconds
)

TimeLayout constants for parsing Unix timestamps in different precisions.

CONNECT (9 declarations)

const (
	CONNECT = http.MethodConnect
	DELETE  = http.MethodDelete
	GET     = http.MethodGet
	HEAD    = http.MethodHead
	OPTIONS = http.MethodOptions
	PATCH   = http.MethodPatch
	POST    = http.MethodPost
	// PROPFIND = "PROPFIND"
	PUT   = http.MethodPut
	TRACE = http.MethodTrace
)

HTTP methods NOTE: Deprecated, please use the stdlib constants directly instead.

MIMEApplicationJSON (17 declarations)

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.1
	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"
)

MIME types

PROPFIND (3 declarations)

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"
	// RouteNotFound is special method type for routes handling "route not found" (404) cases
	RouteNotFound = "echo_route_not_found"
)

HeaderAccept (48 declarations)

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"
	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"
)

Headers

ContextKeyHeaderAllow

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"
)

Version

const (
	// Version of Echo
	Version = "4.16.6"
)

Variables

ErrBadRequest (47 declarations)

var (
	ErrBadRequest                    = NewHTTPError(http.StatusBadRequest)                    // HTTP 400 Bad Request
	ErrUnauthorized                  = NewHTTPError(http.StatusUnauthorized)                  // HTTP 401 Unauthorized
	ErrPaymentRequired               = NewHTTPError(http.StatusPaymentRequired)               // HTTP 402 Payment Required
	ErrForbidden                     = NewHTTPError(http.StatusForbidden)                     // HTTP 403 Forbidden
	ErrNotFound                      = NewHTTPError(http.StatusNotFound)                      // HTTP 404 Not Found
	ErrMethodNotAllowed              = NewHTTPError(http.StatusMethodNotAllowed)              // HTTP 405 Method Not Allowed
	ErrNotAcceptable                 = NewHTTPError(http.StatusNotAcceptable)                 // HTTP 406 Not Acceptable
	ErrProxyAuthRequired             = NewHTTPError(http.StatusProxyAuthRequired)             // HTTP 407 Proxy AuthRequired
	ErrRequestTimeout                = NewHTTPError(http.StatusRequestTimeout)                // HTTP 408 Request Timeout
	ErrConflict                      = NewHTTPError(http.StatusConflict)                      // HTTP 409 Conflict
	ErrGone                          = NewHTTPError(http.StatusGone)                          // HTTP 410 Gone
	ErrLengthRequired                = NewHTTPError(http.StatusLengthRequired)                // HTTP 411 Length Required
	ErrPreconditionFailed            = NewHTTPError(http.StatusPreconditionFailed)            // HTTP 412 Precondition Failed
	ErrStatusRequestEntityTooLarge   = NewHTTPError(http.StatusRequestEntityTooLarge)         // HTTP 413 Payload Too Large
	ErrRequestURITooLong             = NewHTTPError(http.StatusRequestURITooLong)             // HTTP 414 URI Too Long
	ErrUnsupportedMediaType          = NewHTTPError(http.StatusUnsupportedMediaType)          // HTTP 415 Unsupported Media Type
	ErrRequestedRangeNotSatisfiable  = NewHTTPError(http.StatusRequestedRangeNotSatisfiable)  // HTTP 416 Range Not Satisfiable
	ErrExpectationFailed             = NewHTTPError(http.StatusExpectationFailed)             // HTTP 417 Expectation Failed
	ErrTeapot                        = NewHTTPError(http.StatusTeapot)                        // HTTP 418 I'm a teapot
	ErrMisdirectedRequest            = NewHTTPError(http.StatusMisdirectedRequest)            // HTTP 421 Misdirected Request
	ErrUnprocessableEntity           = NewHTTPError(http.StatusUnprocessableEntity)           // HTTP 422 Unprocessable Entity
	ErrLocked                        = NewHTTPError(http.StatusLocked)                        // HTTP 423 Locked
	ErrFailedDependency              = NewHTTPError(http.StatusFailedDependency)              // HTTP 424 Failed Dependency
	ErrTooEarly                      = NewHTTPError(http.StatusTooEarly)                      // HTTP 425 Too Early
	ErrUpgradeRequired               = NewHTTPError(http.StatusUpgradeRequired)               // HTTP 426 Upgrade Required
	ErrPreconditionRequired          = NewHTTPError(http.StatusPreconditionRequired)          // HTTP 428 Precondition Required
	ErrTooManyRequests               = NewHTTPError(http.StatusTooManyRequests)               // HTTP 429 Too Many Requests
	ErrRequestHeaderFieldsTooLarge   = NewHTTPError(http.StatusRequestHeaderFieldsTooLarge)   // HTTP 431 Request Header Fields Too Large
	ErrUnavailableForLegalReasons    = NewHTTPError(http.StatusUnavailableForLegalReasons)    // HTTP 451 Unavailable For Legal Reasons
	ErrInternalServerError           = NewHTTPError(http.StatusInternalServerError)           // HTTP 500 Internal Server Error
	ErrNotImplemented                = NewHTTPError(http.StatusNotImplemented)                // HTTP 501 Not Implemented
	ErrBadGateway                    = NewHTTPError(http.StatusBadGateway)                    // HTTP 502 Bad Gateway
	ErrServiceUnavailable            = NewHTTPError(http.StatusServiceUnavailable)            // HTTP 503 Service Unavailable
	ErrGatewayTimeout                = NewHTTPError(http.StatusGatewayTimeout)                // HTTP 504 Gateway Timeout
	ErrHTTPVersionNotSupported       = NewHTTPError(http.StatusHTTPVersionNotSupported)       // HTTP 505 HTTP Version Not Supported
	ErrVariantAlsoNegotiates         = NewHTTPError(http.StatusVariantAlsoNegotiates)         // HTTP 506 Variant Also Negotiates
	ErrInsufficientStorage           = NewHTTPError(http.StatusInsufficientStorage)           // HTTP 507 Insufficient Storage
	ErrLoopDetected                  = NewHTTPError(http.StatusLoopDetected)                  // HTTP 508 Loop Detected
	ErrNotExtended                   = NewHTTPError(http.StatusNotExtended)                   // HTTP 510 Not Extended
	ErrNetworkAuthenticationRequired = NewHTTPError(http.StatusNetworkAuthenticationRequired) // HTTP 511 Network Authentication Required

	ErrValidatorNotRegistered = errors.New("validator not registered")
	ErrRendererNotRegistered  = errors.New("renderer not registered")
	ErrInvalidRedirectCode    = errors.New("invalid redirect status code")

	// ErrInvalidJSONPCallback is wrapped in the 400 Bad Request error that Context.JSONP and Context.JSONPBlob
	// return when the callback is not a valid JSONP function name. See Context.JSONP.
	ErrInvalidJSONPCallback   = errors.New("invalid JSONP callback")
	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")
)

Errors

ErrInvalidKeyType

var ErrInvalidKeyType = errors.New("invalid key type")

ErrInvalidKeyType is error that is returned when the value is not castable to expected type.

ErrNonExistentKey

var ErrNonExistentKey = errors.New("non existent key")

ErrNonExistentKey is error that is returned when key does not exist

MethodNotAllowedHandler

var MethodNotAllowedHandler = func(c Context) error {

	routerAllowMethods, ok := c.Get(ContextKeyHeaderAllow).(string)
	if ok && routerAllowMethods != "" {
		c.Response().Header().Set(HeaderAllow, routerAllowMethods)
	}
	return ErrMethodNotAllowed
}

MethodNotAllowedHandler is the handler thar router uses in case there was no matching route found but there was another matching routes for that requested URL. Returns an error that results HTTP 405 Method Not Allowed status code.

NotFoundHandler

var NotFoundHandler = func(c Context) error {
	return ErrNotFound
}

NotFoundHandler is the handler that router uses in case there was no matching route found. Returns an error that results HTTP 404 status code.

Functions

ContextGet

func ContextGet[T any](c Context, key string) (T, error)

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

func ContextGetOr[T any](c Context, key string, defaultValue T) (T, error)

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.

FormParam

func FormParam[T any](c Context, key string, opts ...any) (T, error)

FormParam 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

FormParamOr

func FormParamOr[T any](c Context, key string, defaultValue T, opts ...any) (T, error)

FormParamOr 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

FormParams

func FormParams[T any](c Context, key string, opts ...any) ([]T, error)

FormParams 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

FormParamsOr

func FormParamsOr[T any](c Context, key string, defaultValue []T, opts ...any) ([]T, error)

FormParamsOr 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.FormParamsOr[string](c, "tags", []string{})
// If "tags" is missing: returns ([], nil)
// If form parsing fails: returns (nil, error)

See ParseValues for supported types and options

GetPath

func GetPath(r *http.Request) string

GetPath returns RawPath, if it's empty returns Path from URL Difference between RawPath and Path is:

  • Path is where request path is stored. Value is stored in decoded form: /%47%6f%2f becomes /Go/.
  • RawPath is an optional field which only gets set if the default encoding is different from Path.

MustSubFS

func MustSubFS(currentFs fs.FS, fsRoot string) fs.FS

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.

NewBindingError

func NewBindingError(sourceParam string, values []string, message interface{}, internalError error) error

NewBindingError creates new instance of binding error

ParseValue

func ParseValue[T any](value string, opts ...any) (T, error)

ParseValue parses value to generic type

Types that are supported:

  • bool
  • float32
  • float64
  • int
  • int8
  • int16
  • int32
  • int64
  • uint
  • uint8/byte
  • uint16
  • uint32
  • uint64
  • string
  • echo.BindUnmarshaler interface
  • encoding.TextUnmarshaler interface
  • json.Unmarshaler interface
  • time.Duration
  • time.Time use echo.TimeOpts or echo.TimeLayout to set time parsing configuration

ParseValueOr

func ParseValueOr[T any](value string, defaultValue T, opts ...any) (T, error)

ParseValueOr parses value to generic type, when value is empty defaultValue is returned.

Types that are supported:

  • bool
  • float32
  • float64
  • int
  • int8
  • int16
  • int32
  • int64
  • uint
  • uint8/byte
  • uint16
  • uint32
  • uint64
  • string
  • echo.BindUnmarshaler interface
  • encoding.TextUnmarshaler interface
  • json.Unmarshaler interface
  • time.Duration
  • time.Time use echo.TimeOpts or echo.TimeLayout to set time parsing configuration

ParseValues

func ParseValues[T any](values []string, opts ...any) ([]T, error)

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

func ParseValuesOr[T any](values []string, defaultValue []T, opts ...any) ([]T, error)

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

func PathParam[T any](c Context, paramName string, opts ...any) (T, error)

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

func PathParamOr[T any](c Context, paramName string, defaultValue T, opts ...any) (T, error)

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

QueryParam

func QueryParam[T any](c Context, key string, opts ...any) (T, error)

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:

  • Missing key (?other=value): returns (zero, ErrNonExistentKey)
  • Empty value (?key=): returns (zero, nil)
  • Invalid value (?key=abc for int): returns (zero, BindingError)

See ParseValue for supported types and options

QueryParamOr

func QueryParamOr[T any](c Context, key string, defaultValue T, opts ...any) (T, error)

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

func QueryParams[T any](c Context, key string, opts ...any) ([]T, error)

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

QueryParamsOr

func QueryParamsOr[T any](c Context, key string, defaultValue []T, opts ...any) ([]T, error)

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

Types

BindUnmarshaler

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

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.

Binder

type Binder interface {
	Bind(i interface{}, c Context) error
}

Binder is the interface that wraps the Bind method.

BindingError

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:"-"`
}

BindingError represents an error that occurred while binding request data.

BindingError.Error

func (be *BindingError) Error() string

Error returns error message

Context

type Context interface {
	// Request returns `*http.Request`.
	Request() *http.Request

	// SetRequest sets `*http.Request`.
	SetRequest(r *http.Request)

	// SetResponse sets `*Response`.
	SetResponse(r *Response)

	// Response returns `*Response`.
	Response() *Response

	// IsTLS returns true if HTTP connection is TLS otherwise false.
	IsTLS() bool

	// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
	IsWebSocket() bool

	// Scheme returns the HTTP protocol scheme, `http` or `https`.
	Scheme() string

	// RealIP returns the client IP from Echo#IPExtractor, or the connection peer
	// when no extractor is configured. Forwarding headers are ignored by default.
	// Applications behind proxies must configure an extractor that trusts only
	// their own proxies to recover individual client addresses.
	RealIP() string

	// Path returns the registered path for the handler.
	Path() string

	// SetPath sets the registered path for the handler.
	SetPath(p string)

	// Param returns path parameter by name.
	Param(name string) string

	// ParamNames returns path parameter names.
	ParamNames() []string

	// SetParamNames sets path parameter names.
	SetParamNames(names ...string)

	// ParamValues returns path parameter values.
	ParamValues() []string

	// SetParamValues sets path parameter values.
	SetParamValues(values ...string)

	// QueryParam returns the query param for the provided name.
	QueryParam(name string) string

	// QueryParams returns the query parameters as `url.Values`.
	QueryParams() url.Values

	// QueryString returns the URL query string.
	QueryString() string

	// FormValue returns the form field value for the provided name.
	FormValue(name string) string

	// FormParams returns the form parameters as `url.Values`.
	FormParams() (url.Values, error)

	// FormFile returns the multipart form file for the provided name.
	FormFile(name string) (*multipart.FileHeader, error)

	// MultipartForm returns the multipart form.
	MultipartForm() (*multipart.Form, error)

	// Cookie returns the named cookie provided in the request.
	Cookie(name string) (*http.Cookie, error)

	// SetCookie adds a `Set-Cookie` header in HTTP response.
	SetCookie(cookie *http.Cookie)

	// Cookies returns the HTTP cookies sent with the request.
	Cookies() []*http.Cookie

	// Get retrieves data from the context.
	Get(key string) any

	// Set saves data in the context.
	Set(key string, val any)

	// Bind binds path params, query params and the request body into provided type `i`. The default binder
	// binds body based on Content-Type header.
	Bind(i any) error

	// Validate validates provided `i`. It is usually called after `Context#Bind()`.
	// Validator must be registered using `Echo#Validator`.
	Validate(i any) error

	// Render renders a template with data and sends a text/html response with status
	// code. Renderer must be registered using `Echo.Renderer`.
	Render(code int, name string, data any) error

	// HTML sends an HTTP response with status code.
	HTML(code int, html string) error

	// HTMLBlob sends an HTTP blob response with status code.
	HTMLBlob(code int, b []byte) error

	// String sends a string response with status code.
	String(code int, s string) error

	// JSON sends a JSON response with status code.
	JSON(code int, i any) error

	// JSONPretty sends a pretty-print JSON with status code.
	JSONPretty(code int, i any, indent string) error

	// JSONBlob sends a JSON blob response with status code.
	JSONBlob(code int, b []byte) error

	// JSONP sends a JSONP response with status code. It uses `callback` to construct
	// the JSONP payload.
	//
	// The callback must be empty, a JavaScript identifier or a dot-separated path of identifiers using only ASCII
	// letters, digits, `_` and `$`. Otherwise nothing is written and a 400 Bad Request error wrapping
	// ErrInvalidJSONPCallback is returned. The response has the `X-Content-Type-Options: nosniff` header.
	//
	// Any website can load a JSONP response with a <script> tag, including the user's cookies. Do not use JSONP for
	// data that requires authentication; use JSON with CORS instead.
	JSONP(code int, callback string, i any) error

	// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
	// to construct the JSONP payload. The callback is validated like in Context.JSONP.
	JSONPBlob(code int, callback string, b []byte) error

	// XML sends an XML response with status code.
	XML(code int, i any) error

	// XMLPretty sends a pretty-print XML with status code.
	XMLPretty(code int, i any, indent string) error

	// XMLBlob sends an XML blob response with status code.
	XMLBlob(code int, b []byte) error

	// Blob sends a blob response with status code and content type.
	Blob(code int, contentType string, b []byte) error

	// Stream sends a streaming response with status code and content type.
	Stream(code int, contentType string, r io.Reader) error

	// File sends a response with the content of the file.
	File(file string) error

	// Attachment sends a response as attachment, prompting client to save the
	// file.
	Attachment(file string, name string) error

	// Inline sends a response as inline, opening the file in the browser.
	Inline(file string, name string) error

	// NoContent sends a response with no body and a status code.
	NoContent(code int) error

	// Redirect redirects the request to a provided URL with status code.
	Redirect(code int, url string) error

	// Error invokes the registered global HTTP error handler. Generally used by middleware.
	// A side-effect of calling global error handler is that now Response has been committed (sent to the client) and
	// middlewares up in chain can not change Response status code or Response body anymore.
	//
	// Avoid using this method in handlers as no middleware will be able to effectively handle errors after that.
	Error(err error)

	// Handler returns the matched handler by router.
	Handler() HandlerFunc

	// SetHandler sets the matched handler by router.
	SetHandler(h HandlerFunc)

	// Logger returns the `Logger` instance.
	Logger() Logger

	// SetLogger Set the logger
	SetLogger(l Logger)

	// Echo returns the `Echo` instance.
	Echo() *Echo

	// Reset resets the context after request completes. It must be called along
	// with `Echo#AcquireContext()` and `Echo#ReleaseContext()`.
	// See `Echo#ServeHTTP()`
	Reset(r *http.Request, w http.ResponseWriter)
}

Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.

DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface. For path, query, header, and form binding, time.Time and *time.Time fields (not slices) may use a format tag: "date-time" uses the standard RFC3339 decoding, "date-time-local" accepts "2006-01-02T15:04:05" with optional fractional seconds, "date" accepts "2006-01-02", and other values specify Go time layouts. "date", "date-time-local", and layouts without a timezone give UTC times. JSON and XML decoding do not use this tag. HTML datetime-local inputs omit seconds by default, so bind them with a Go layout such as "2006-01-02T15:04" instead of "date-time-local".

DefaultBinder.Bind

func (b *DefaultBinder) Bind(i interface{}, c Context) (err error)

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 binded values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams.

DefaultBinder.BindBody

func (b *DefaultBinder) BindBody(c Context, i interface{}) (err error)

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

DefaultBinder.BindHeaders

func (b *DefaultBinder) BindHeaders(c Context, i interface{}) error

BindHeaders binds HTTP headers to a bindable object

Showing entries 1–40 of 249. Use Contents to jump to any section or symbol.

Dependency graph