Documentation
¶
Overview ¶
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
Index ¶
- Constants
- Variables
- func BindBody(c *Context, target any) (err error)
- func BindHeaders(c *Context, target any) error
- func BindPathValues(c *Context, target any) error
- func BindQueryParams(c *Context, target any) error
- func ContextGet[T any](c *Context, key string) (T, error)
- func ContextGetOr[T any](c *Context, key string, defaultValue T) (T, error)
- func FormValue[T any](c *Context, key string, opts ...any) (T, error)
- func FormValueOr[T any](c *Context, key string, defaultValue T, opts ...any) (T, error)
- func FormValues[T any](c *Context, key string, opts ...any) ([]T, error)
- func FormValuesOr[T any](c *Context, key string, defaultValue []T, opts ...any) ([]T, error)
- func HandlerName(h HandlerFunc) string
- func MustSubFS(currentFs fs.FS, fsRoot string) fs.FS
- func NewBindingError(sourceParam string, values []string, message string, err error) error
- func ParseValue[T any](value string, opts ...any) (T, error)
- func ParseValueOr[T any](value string, defaultValue T, opts ...any) (T, error)
- func ParseValues[T any](values []string, opts ...any) ([]T, error)
- func ParseValuesOr[T any](values []string, defaultValue []T, opts ...any) ([]T, error)
- func PathParam[T any](c *Context, paramName string, opts ...any) (T, error)
- func PathParamOr[T any](c *Context, paramName string, defaultValue T, opts ...any) (T, error)
- func QueryParam[T any](c *Context, key string, opts ...any) (T, error)
- func QueryParamOr[T any](c *Context, key string, defaultValue T, opts ...any) (T, error)
- func QueryParams[T any](c *Context, key string, opts ...any) ([]T, error)
- func QueryParamsOr[T any](c *Context, key string, defaultValue []T, opts ...any) ([]T, error)
- type AddRouteError
- type BindUnmarshaler
- type Binder
- type BindingError
- type Config
- type Context
- func (c *Context) Attachment(file, name string) error
- func (c *Context) Bind(i any) error
- func (c *Context) Blob(code int, contentType string, b []byte) (err error)
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) Echo() *Echo
- func (c *Context) File(file string) error
- func (c *Context) FileFS(file string, filesystem fs.FS) error
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormValue(name string) string
- func (c *Context) FormValueOr(name, defaultValue string) string
- func (c *Context) FormValues() (url.Values, error)
- func (c *Context) Get(key string) any
- func (c *Context) HTML(code int, html string) (err error)
- func (c *Context) HTMLBlob(code int, b []byte) (err error)
- func (c *Context) InitializeRoute(ri *RouteInfo, pathValues *PathValues)
- func (c *Context) Inline(file, name string) error
- func (c *Context) IsTLS() bool
- func (c *Context) IsWebSocket() bool
- func (c *Context) JSON(code int, i any) (err error)
- func (c *Context) JSONBlob(code int, b []byte) (err error)
- func (c *Context) JSONP(code int, callback string, i any) (err error)
- func (c *Context) JSONPBlob(code int, callback string, b []byte) (err error)
- func (c *Context) JSONPretty(code int, i any, indent string) (err error)
- func (c *Context) Logger() *slog.Logger
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) NoContent(code int) error
- func (c *Context) Param(name string) string
- func (c *Context) ParamOr(name, defaultValue string) string
- func (c *Context) Path() string
- func (c *Context) PathValues() PathValues
- func (c *Context) QueryParam(name string) string
- func (c *Context) QueryParamOr(name, defaultValue string) string
- func (c *Context) QueryParams() url.Values
- func (c *Context) QueryString() string
- func (c *Context) RealIP() string
- func (c *Context) Redirect(code int, url string) error
- func (c *Context) Render(code int, name string, data any) (err error)
- func (c *Context) Request() *http.Request
- func (c *Context) Reset(r *http.Request, w http.ResponseWriter)
- func (c *Context) Response() http.ResponseWriter
- func (c *Context) RouteInfo() RouteInfo
- func (c *Context) Scheme() string
- func (c *Context) Set(key string, val any)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetLogger(logger *slog.Logger)
- func (c *Context) SetPath(p string)
- func (c *Context) SetPathValues(pathValues PathValues)
- func (c *Context) SetRequest(r *http.Request)
- func (c *Context) SetResponse(r http.ResponseWriter)
- func (c *Context) Stream(code int, contentType string, r io.Reader) (err error)
- func (c *Context) String(code int, s string) (err error)
- func (c *Context) Validate(i any) error
- func (c *Context) XML(code int, i any) (err error)
- func (c *Context) XMLBlob(code int, b []byte) (err error)
- func (c *Context) XMLPretty(code int, i any, indent string) (err error)
- type DefaultBinder
- type DefaultJSONSerializer
- type DefaultRouter
- type Echo
- func (e *Echo) AcquireContext() *Context
- func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
- func (e *Echo) AddRoute(route Route) (RouteInfo, error)
- func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
- func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) File(path, file string, middleware ...MiddlewareFunc) RouteInfo
- func (e *Echo) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group)
- func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) Match(methods []string, path string, handler HandlerFunc, ...) Routes
- func (e *Echo) Middlewares() []MiddlewareFunc
- func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) *Context
- func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) Pre(middleware ...MiddlewareFunc)
- func (e *Echo) PreMiddlewares() []MiddlewareFunc
- func (e *Echo) ReleaseContext(c *Context)
- func (e *Echo) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) Router() Router
- func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (e *Echo) Start(address string) error
- func (e *Echo) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo
- func (e *Echo) StaticFS(pathPrefix string, filesystem fs.FS, middleware ...MiddlewareFunc) RouteInfo
- func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (e *Echo) Use(middleware ...MiddlewareFunc)
- type Group
- func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
- func (g *Group) AddRoute(route Route) (RouteInfo, error)
- func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
- func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) File(path, file string, middleware ...MiddlewareFunc) RouteInfo
- func (g *Group) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) RouteInfo
- func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) (sg *Group)
- func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) Match(methods []string, path string, handler HandlerFunc, ...) Routes
- func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo
- func (g *Group) StaticFS(pathPrefix string, filesystem fs.FS, middleware ...MiddlewareFunc) RouteInfo
- func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
- func (g *Group) Use(middleware ...MiddlewareFunc)
- type HTTPError
- type HTTPErrorHandler
- type HTTPStatusCoder
- type HandlerFunc
- type IPExtractor
- type JSONSerializer
- type MiddlewareConfigurator
- type MiddlewareFunc
- type PathValue
- type PathValues
- type Renderer
- type Response
- func (r *Response) After(fn func())
- func (r *Response) Before(fn func())
- func (r *Response) Flush()
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) Unwrap() http.ResponseWriter
- func (r *Response) Write(b []byte) (n int, err error)
- func (r *Response) WriteHeader(code int)
- type Route
- type RouteInfo
- type Router
- type RouterConfig
- type Routes
- func (r Routes) Clone() Routes
- func (r Routes) FilterByMethod(method string) (Routes, error)
- func (r Routes) FilterByName(name string) (Routes, error)
- func (r Routes) FilterByPath(path string) (Routes, error)
- func (r Routes) FindByMethodPath(method string, path string) (RouteInfo, error)
- func (r Routes) Reverse(routeName string, pathValues ...any) (string, error)
- type StartConfig
- type TemplateRenderer
- type TimeLayout
- type TimeOpts
- type TrustOption
- type Validator
- type ValueBinder
- func (b *ValueBinder) BindError() error
- func (b *ValueBinder) BindErrors() []error
- func (b *ValueBinder) BindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder
- func (b *ValueBinder) BindWithDelimiter(sourceParam string, dest any, delimiter string) *ValueBinder
- func (b *ValueBinder) Bool(sourceParam string, dest *bool) *ValueBinder
- func (b *ValueBinder) Bools(sourceParam string, dest *[]bool) *ValueBinder
- func (b *ValueBinder) Byte(sourceParam string, dest *byte) *ValueBinder
- func (b *ValueBinder) CustomFunc(sourceParam string, customFunc func(values []string) []error) *ValueBinder
- func (b *ValueBinder) Duration(sourceParam string, dest *time.Duration) *ValueBinder
- func (b *ValueBinder) Durations(sourceParam string, dest *[]time.Duration) *ValueBinder
- func (b *ValueBinder) FailFast(value bool) *ValueBinder
- func (b *ValueBinder) Float32(sourceParam string, dest *float32) *ValueBinder
- func (b *ValueBinder) Float32s(sourceParam string, dest *[]float32) *ValueBinder
- func (b *ValueBinder) Float64(sourceParam string, dest *float64) *ValueBinder
- func (b *ValueBinder) Float64s(sourceParam string, dest *[]float64) *ValueBinder
- func (b *ValueBinder) Int(sourceParam string, dest *int) *ValueBinder
- func (b *ValueBinder) Int16(sourceParam string, dest *int16) *ValueBinder
- func (b *ValueBinder) Int16s(sourceParam string, dest *[]int16) *ValueBinder
- func (b *ValueBinder) Int32(sourceParam string, dest *int32) *ValueBinder
- func (b *ValueBinder) Int32s(sourceParam string, dest *[]int32) *ValueBinder
- func (b *ValueBinder) Int64(sourceParam string, dest *int64) *ValueBinder
- func (b *ValueBinder) Int64s(sourceParam string, dest *[]int64) *ValueBinder
- func (b *ValueBinder) Int8(sourceParam string, dest *int8) *ValueBinder
- func (b *ValueBinder) Int8s(sourceParam string, dest *[]int8) *ValueBinder
- func (b *ValueBinder) Ints(sourceParam string, dest *[]int) *ValueBinder
- func (b *ValueBinder) JSONUnmarshaler(sourceParam string, dest json.Unmarshaler) *ValueBinder
- func (b *ValueBinder) MustBindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder
- func (b *ValueBinder) MustBindWithDelimiter(sourceParam string, dest any, delimiter string) *ValueBinder
- func (b *ValueBinder) MustBool(sourceParam string, dest *bool) *ValueBinder
- func (b *ValueBinder) MustBools(sourceParam string, dest *[]bool) *ValueBinder
- func (b *ValueBinder) MustByte(sourceParam string, dest *byte) *ValueBinder
- func (b *ValueBinder) MustCustomFunc(sourceParam string, customFunc func(values []string) []error) *ValueBinder
- func (b *ValueBinder) MustDuration(sourceParam string, dest *time.Duration) *ValueBinder
- func (b *ValueBinder) MustDurations(sourceParam string, dest *[]time.Duration) *ValueBinder
- func (b *ValueBinder) MustFloat32(sourceParam string, dest *float32) *ValueBinder
- func (b *ValueBinder) MustFloat32s(sourceParam string, dest *[]float32) *ValueBinder
- func (b *ValueBinder) MustFloat64(sourceParam string, dest *float64) *ValueBinder
- func (b *ValueBinder) MustFloat64s(sourceParam string, dest *[]float64) *ValueBinder
- func (b *ValueBinder) MustInt(sourceParam string, dest *int) *ValueBinder
- func (b *ValueBinder) MustInt16(sourceParam string, dest *int16) *ValueBinder
- func (b *ValueBinder) MustInt16s(sourceParam string, dest *[]int16) *ValueBinder
- func (b *ValueBinder) MustInt32(sourceParam string, dest *int32) *ValueBinder
- func (b *ValueBinder) MustInt32s(sourceParam string, dest *[]int32) *ValueBinder
- func (b *ValueBinder) MustInt64(sourceParam string, dest *int64) *ValueBinder
- func (b *ValueBinder) MustInt64s(sourceParam string, dest *[]int64) *ValueBinder
- func (b *ValueBinder) MustInt8(sourceParam string, dest *int8) *ValueBinder
- func (b *ValueBinder) MustInt8s(sourceParam string, dest *[]int8) *ValueBinder
- func (b *ValueBinder) MustInts(sourceParam string, dest *[]int) *ValueBinder
- func (b *ValueBinder) MustJSONUnmarshaler(sourceParam string, dest json.Unmarshaler) *ValueBinder
- func (b *ValueBinder) MustString(sourceParam string, dest *string) *ValueBinder
- func (b *ValueBinder) MustStrings(sourceParam string, dest *[]string) *ValueBinder
- func (b *ValueBinder) MustTextUnmarshaler(sourceParam string, dest encoding.TextUnmarshaler) *ValueBinder
- func (b *ValueBinder) MustTime(sourceParam string, dest *time.Time, layout string) *ValueBinder
- func (b *ValueBinder) MustTimes(sourceParam string, dest *[]time.Time, layout string) *ValueBinder
- func (b *ValueBinder) MustUint(sourceParam string, dest *uint) *ValueBinder
- func (b *ValueBinder) MustUint16(sourceParam string, dest *uint16) *ValueBinder
- func (b *ValueBinder) MustUint16s(sourceParam string, dest *[]uint16) *ValueBinder
- func (b *ValueBinder) MustUint32(sourceParam string, dest *uint32) *ValueBinder
- func (b *ValueBinder) MustUint32s(sourceParam string, dest *[]uint32) *ValueBinder
- func (b *ValueBinder) MustUint64(sourceParam string, dest *uint64) *ValueBinder
- func (b *ValueBinder) MustUint64s(sourceParam string, dest *[]uint64) *ValueBinder
- func (b *ValueBinder) MustUint8(sourceParam string, dest *uint8) *ValueBinder
- func (b *ValueBinder) MustUint8s(sourceParam string, dest *[]uint8) *ValueBinder
- func (b *ValueBinder) MustUints(sourceParam string, dest *[]uint) *ValueBinder
- func (b *ValueBinder) MustUnixTime(sourceParam string, dest *time.Time) *ValueBinder
- func (b *ValueBinder) MustUnixTimeMilli(sourceParam string, dest *time.Time) *ValueBinder
- func (b *ValueBinder) MustUnixTimeNano(sourceParam string, dest *time.Time) *ValueBinder
- func (b *ValueBinder) String(sourceParam string, dest *string) *ValueBinder
- func (b *ValueBinder) Strings(sourceParam string, dest *[]string) *ValueBinder
- func (b *ValueBinder) TextUnmarshaler(sourceParam string, dest encoding.TextUnmarshaler) *ValueBinder
- func (b *ValueBinder) Time(sourceParam string, dest *time.Time, layout string) *ValueBinder
- func (b *ValueBinder) Times(sourceParam string, dest *[]time.Time, layout string) *ValueBinder
- func (b *ValueBinder) Uint(sourceParam string, dest *uint) *ValueBinder
- func (b *ValueBinder) Uint16(sourceParam string, dest *uint16) *ValueBinder
- func (b *ValueBinder) Uint16s(sourceParam string, dest *[]uint16) *ValueBinder
- func (b *ValueBinder) Uint32(sourceParam string, dest *uint32) *ValueBinder
- func (b *ValueBinder) Uint32s(sourceParam string, dest *[]uint32) *ValueBinder
- func (b *ValueBinder) Uint64(sourceParam string, dest *uint64) *ValueBinder
- func (b *ValueBinder) Uint64s(sourceParam string, dest *[]uint64) *ValueBinder
- func (b *ValueBinder) Uint8(sourceParam string, dest *uint8) *ValueBinder
- func (b *ValueBinder) Uint8s(sourceParam string, dest *[]uint8) *ValueBinder
- func (b *ValueBinder) Uints(sourceParam string, dest *[]uint) *ValueBinder
- func (b *ValueBinder) UnixTime(sourceParam string, dest *time.Time) *ValueBinder
- func (b *ValueBinder) UnixTimeMilli(sourceParam string, dest *time.Time) *ValueBinder
- func (b *ValueBinder) UnixTimeNano(sourceParam string, dest *time.Time) *ValueBinder
Examples ¶
Constants ¶
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.
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" )
MIME types
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" // 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" )
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" )
Headers
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.0.0-alpha"
)
Variables ¶
var ( ErrBadRequest = &httpError{http.StatusBadRequest} // 400 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 )
Following errors can produce HTTP status code by implementing HTTPStatusCoder interface
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") )
Following errors fall into 500 (InternalServerError) category
var ErrInvalidKeyType = errors.New("invalid key type")
ErrInvalidKeyType is error that is returned when the value is not castable to expected type.
var ErrNonExistentKey = errors.New("non existent key")
ErrNonExistentKey is error that is returned when key does not exist
Functions ¶
func BindBody ¶
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
func BindHeaders ¶
BindHeaders binds HTTP headers to a bindable object
func BindPathValues ¶
BindPathValues binds path parameter values to bindable object
func BindQueryParams ¶
BindQueryParams binds query params to bindable object
func ContextGet ¶
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.
func ContextGetOr ¶
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.
func FormValue ¶
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
func FormValueOr ¶
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
func FormValues ¶
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
func FormValuesOr ¶
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
func HandlerName ¶
func HandlerName(h HandlerFunc) string
HandlerName returns string name for given function.
func MustSubFS ¶
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.
func NewBindingError ¶
NewBindingError creates new instance of binding error
func ParseValue ¶
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
func ParseValueOr ¶
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
func ParseValues ¶
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
func ParseValuesOr ¶
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
func PathParam ¶
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
func PathParamOr ¶
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
func QueryParam ¶
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
func QueryParamOr ¶
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
func QueryParams ¶
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
func QueryParamsOr ¶
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 ¶
type AddRouteError ¶
AddRouteError is error returned by Router.Add containing information what actual route adding failed. Useful for mass adding (i.e. Any() routes)
func (*AddRouteError) Error ¶
func (e *AddRouteError) Error() string
func (*AddRouteError) Unwrap ¶
func (e *AddRouteError) Unwrap() error
type 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.
type 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.
type Config ¶
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
}
Config is configuration for NewWithConfig function
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.
func NewContext ¶
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.
func (*Context) Attachment ¶
Attachment sends a response as attachment, prompting client to save the file.
func (*Context) Bind ¶
Bind binds path params, query params and the request body into provided type `i`. The default binder binds body based on Content-Type header.
func (*Context) FileFS ¶
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/images` embeds files with paths including `assets/images` as their prefix.
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the multipart form file for the provided name.
func (*Context) FormValueOr ¶
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
func (*Context) FormValues ¶
FormValues returns the form field values as `url.Values`.
func (*Context) Get ¶
Get retrieves data from the context. Method returns any(nil) when key does not exist which is different from typed nil (eg. []byte(nil)).
func (*Context) InitializeRoute ¶
func (c *Context) InitializeRoute(ri *RouteInfo, pathValues *PathValues)
InitializeRoute sets the route related variables of this request to the context.
func (*Context) IsWebSocket ¶
IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) JSONPBlob ¶
JSONPBlob sends a JSONP blob response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) JSONPretty ¶
JSONPretty sends a pretty-print JSON with status code.
func (*Context) MultipartForm ¶
MultipartForm returns the multipart form.
func (*Context) ParamOr ¶
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: * route `/release-:version/bin` and request URL is `/release-/bin` * route `/api/:version/image.jpg` and request URL is `/api//image.jpg` but not when path parameter is last part of route path * route `/download/file.:ext` will not match request `/download/file.`
func (*Context) PathValues ¶
func (c *Context) PathValues() PathValues
PathValues returns path parameter values.
func (*Context) QueryParam ¶
QueryParam returns the query param for the provided name.
func (*Context) QueryParamOr ¶
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")`
func (*Context) QueryParams ¶
QueryParams returns the query parameters as `url.Values`.
func (*Context) QueryString ¶
QueryString returns the URL query string.
func (*Context) RealIP ¶
RealIP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header. The behavior can be configured using `Echo#IPExtractor`.
func (*Context) Render ¶
Render renders a template with data and sends a text/html response with status code. Renderer must be registered using `Echo.Renderer`.
func (*Context) Reset ¶
func (c *Context) Reset(r *http.Request, w http.ResponseWriter)
Reset resets the context after request completes. It must be called along with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. See `Echo#ServeHTTP()`
func (*Context) Response ¶
func (c *Context) Response() http.ResponseWriter
Response returns `*Response`.
func (*Context) RouteInfo ¶
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: * Context is accessed before Routing is done. For example inside Pre middlewares (`e.Pre()`) * Router did not find matching route - 404 (route not found) * Router did not find matching route with same method - 405 (method not allowed)
func (*Context) SetPathValues ¶
func (c *Context) SetPathValues(pathValues PathValues)
SetPathValues sets path parameters for current request.
func (*Context) SetRequest ¶
SetRequest sets `*http.Request`.
func (*Context) SetResponse ¶
func (c *Context) SetResponse(r http.ResponseWriter)
SetResponse sets `*http.ResponseWriter`. Some middleware require that given ResponseWriter implements following method `Unwrap() http.ResponseWriter` which eventually should return echo.Response instance.
func (*Context) Validate ¶
Validate validates provided `i`. It is usually called after `Context#Bind()`. Validator must be registered using `Echo#Validator`.
type DefaultBinder ¶
type DefaultBinder struct{}
DefaultBinder is the default implementation of the Binder interface.
func (*DefaultBinder) Bind ¶
func (b *DefaultBinder) Bind(c *Context, target any) 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 bound values. For single source binding use their own methods BindBody, BindQueryParams, BindPathValues.
type DefaultJSONSerializer ¶
type DefaultJSONSerializer struct{}
DefaultJSONSerializer implements JSON encoding using encoding/json.
func (DefaultJSONSerializer) Deserialize ¶
func (d DefaultJSONSerializer) Deserialize(c *Context, target any) error
Deserialize reads a JSON from a request body and converts it into an interface.
type DefaultRouter ¶
type DefaultRouter struct {
// contains filtered or unexported fields
}
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.
func NewRouter ¶
func NewRouter(config RouterConfig) *DefaultRouter
NewRouter returns a new Router instance.
func (*DefaultRouter) Add ¶
func (r *DefaultRouter) Add(route Route) (RouteInfo, error)
Add registers a new route for method and path with matching handler.
func (*DefaultRouter) Remove ¶
func (r *DefaultRouter) Remove(method string, path string) error
Remove unregisters registered route
func (*DefaultRouter) Route ¶
func (r *DefaultRouter) Route(c *Context) HandlerFunc
Route looks up a handler registered for method and path. It also parses URL for path parameters and loads them into context.
For performance:
- Get context from `Echo#AcquireContext()` - Reset it `Context#Reset()` - Return it `Echo#ReleaseContext()`.
func (*DefaultRouter) Routes ¶
func (r *DefaultRouter) Routes() Routes
Routes returns all registered routes
type Echo ¶
type Echo struct {
Binder Binder
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
}
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.
func NewVirtualHostHandler ¶
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.
func NewWithConfig ¶
NewWithConfig creates an instance of Echo with given configuration.
func (*Echo) AcquireContext ¶
AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.
func (*Echo) Add ¶
func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
Add registers a new route for an HTTP method and path with matching handler in the router with optional route-level middleware.
func (*Echo) Any ¶
func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
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.
func (*Echo) CONNECT ¶
func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) DELETE ¶
func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
DELETE registers a new DELETE route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) File ¶
func (e *Echo) File(path, file string, middleware ...MiddlewareFunc) RouteInfo
File registers a new route with path to serve a static file with optional route-level middleware. Panics on error.
func (*Echo) FileFS ¶
FileFS registers a new route with path to serve file from the provided file system.
func (*Echo) GET ¶
func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
GET registers a new GET route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) Group ¶
func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group)
Group creates a new router group with prefix and optional group-level middleware.
func (*Echo) HEAD ¶
func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) Match ¶
func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) Routes
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.
func (*Echo) Middlewares ¶
func (e *Echo) Middlewares() []MiddlewareFunc
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.
func (*Echo) NewContext ¶
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.
func (*Echo) OPTIONS ¶
func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
OPTIONS registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) PATCH ¶
func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
PATCH registers a new PATCH route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) POST ¶
func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
POST registers a new POST route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) PUT ¶
func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
PUT registers a new PUT route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) Pre ¶
func (e *Echo) Pre(middleware ...MiddlewareFunc)
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.
func (*Echo) PreMiddlewares ¶
func (e *Echo) PreMiddlewares() []MiddlewareFunc
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.
func (*Echo) ReleaseContext ¶
ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.
func (*Echo) RouteNotFound ¶
func (e *Echo) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
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) })`
func (*Echo) ServeHTTP ¶
func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (*Echo) Start ¶
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())
}
func (*Echo) Static ¶
func (e *Echo) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo
Static registers a new route with path prefix to serve static files from the provided root directory.
func (*Echo) StaticFS ¶
func (e *Echo) StaticFS(pathPrefix string, filesystem fs.FS, middleware ...MiddlewareFunc) RouteInfo
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/images` embeds files with paths including `assets/images` as their prefix.
func (*Echo) TRACE ¶
func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware. Panics on error.
func (*Echo) Use ¶
func (e *Echo) Use(middleware ...MiddlewareFunc)
Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
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.
func (*Group) Add ¶
func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
Add implements `Echo#Add()` for sub-routes within the Group. Panics on error.
func (*Group) Any ¶
func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo
Any implements `Echo#Any()` for sub-routes within the Group. Panics on error.
func (*Group) CONNECT ¶
func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error.
func (*Group) DELETE ¶
func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error.
func (*Group) File ¶
func (g *Group) File(path, file string, middleware ...MiddlewareFunc) RouteInfo
File implements `Echo#File()` for sub-routes within the Group. Panics on error.
func (*Group) GET ¶
func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
GET implements `Echo#GET()` for sub-routes within the Group. Panics on error.
func (*Group) Group ¶
func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) (sg *Group)
Group creates a new sub-group with prefix and optional sub-group-level middleware. Important! Group middlewares are only executed in case there was exact route match and not for 404 (not found) or 405 (method not allowed) cases. If this kind of behaviour is needed then add a catch-all route `/*` for the group which handler returns always 404
func (*Group) HEAD ¶
func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
HEAD implements `Echo#HEAD()` for sub-routes within the Group. Panics on error.
func (*Group) Match ¶
func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) Routes
Match implements `Echo#Match()` for sub-routes within the Group. Panics on error.
func (*Group) OPTIONS ¶
func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. Panics on error.
func (*Group) PATCH ¶
func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
PATCH implements `Echo#PATCH()` for sub-routes within the Group. Panics on error.
func (*Group) POST ¶
func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
POST implements `Echo#POST()` for sub-routes within the Group. Panics on error.
func (*Group) PUT ¶
func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
PUT implements `Echo#PUT()` for sub-routes within the Group. Panics on error.
func (*Group) RouteNotFound ¶
func (g *Group) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group.
Example: `g.RouteNotFound("/*", func(c *echo.Context) error { return c.NoContent(http.StatusNotFound) })`
func (*Group) Static ¶
func (g *Group) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo
Static implements `Echo#Static()` for sub-routes within the Group.
func (*Group) StaticFS ¶
func (g *Group) StaticFS(pathPrefix string, filesystem fs.FS, middleware ...MiddlewareFunc) RouteInfo
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/images` embeds files with paths including `assets/images` as their prefix.
func (*Group) TRACE ¶
func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo
TRACE implements `Echo#TRACE()` for sub-routes within the Group. Panics on error.
func (*Group) Use ¶
func (g *Group) Use(middleware ...MiddlewareFunc)
Use implements `Echo#Use()` for sub-routes within the Group. Group middlewares are not executed on request when there is no matching route found.
type HTTPError ¶
type HTTPError struct {
// Code is status code for HTTP response
Code int `json:"-"`
Message string `json:"message"`
// contains filtered or unexported fields
}
HTTPError represents an error that occurred while handling a request.
func NewHTTPError ¶
NewHTTPError creates new instance of HTTPError
func (*HTTPError) StatusCode ¶
StatusCode returns status code for HTTP response
type HTTPErrorHandler ¶
HTTPErrorHandler is a centralized HTTP error handler.
func DefaultHTTPErrorHandler ¶
func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler
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.
Example ¶
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
// run tests as external package to get real feel for API
package main
import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v5"
"net/http"
"net/http/httptest"
)
func main() {
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())
}
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"}}
type HTTPStatusCoder ¶
type HTTPStatusCoder interface {
StatusCode() int
}
HTTPStatusCoder is interface that errors can implement to produce status code for HTTP response
type HandlerFunc ¶
HandlerFunc defines a function to serve HTTP requests.
func StaticDirectoryHandler ¶
func StaticDirectoryHandler(fileSystem fs.FS, disablePathUnescaping bool) HandlerFunc
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.
func StaticFileHandler ¶
func StaticFileHandler(file string, filesystem fs.FS) HandlerFunc
StaticFileHandler creates handler function to serve file from provided file system
func WrapHandler ¶
func WrapHandler(h http.Handler) HandlerFunc
WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
type IPExtractor ¶
IPExtractor 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.
func ExtractIPDirect ¶
func ExtractIPDirect() IPExtractor
ExtractIPDirect extracts IP address using actual IP address. Use this if your server faces to internet directory (i.e.: uses no proxy).
func ExtractIPFromRealIPHeader ¶
func ExtractIPFromRealIPHeader(options ...TrustOption) IPExtractor
ExtractIPFromRealIPHeader extracts IP address using x-real-ip header. Use this if you put proxy which uses this header.
func ExtractIPFromXFFHeader ¶
func ExtractIPFromXFFHeader(options ...TrustOption) IPExtractor
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]).
type JSONSerializer ¶
type JSONSerializer interface {
Serialize(c *Context, target any, indent string) error
Deserialize(c *Context, target any) error
}
JSONSerializer is the interface that encodes and decodes JSON to and from interfaces.
type MiddlewareConfigurator ¶
type MiddlewareConfigurator interface {
ToMiddleware() (MiddlewareFunc, error)
}
MiddlewareConfigurator defines interface for creating middleware handlers with possibility to return configuration errors instead of panicking.
type MiddlewareFunc ¶
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
MiddlewareFunc defines a function to process middleware.
func WrapMiddleware ¶
func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc
WrapMiddleware wraps `func(http.Handler) http.Handler` into `echo.MiddlewareFunc`
type PathValues ¶
type PathValues []PathValue
PathValues is collections of PathValue instances with various helper methods
type Response ¶
type Response struct {
http.ResponseWriter
Status int
Size int64
Committed bool
// contains filtered or unexported fields
}
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
func NewResponse ¶
func NewResponse(w http.ResponseWriter, logger *slog.Logger) (r *Response)
NewResponse creates a new instance of Response.
func UnwrapResponse ¶
func UnwrapResponse(rw http.ResponseWriter) (*Response, error)
UnwrapResponse unwraps given ResponseWriter to return contexts original Echo Response. rw has to implement following method `Unwrap() http.ResponseWriter`
func (*Response) After ¶
func (r *Response) After(fn func())
After registers a function which is called just after the response is written.
func (*Response) Before ¶
func (r *Response) Before(fn func())
Before registers a function which is called just before the response (status) is written.
func (*Response) Flush ¶
func (r *Response) Flush()
Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)
func (*Response) Hijack ¶
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(https://golang.org/pkg/net/http/#Hijacker)
func (*Response) Unwrap ¶
func (r *Response) Unwrap() http.ResponseWriter
Unwrap returns the original http.ResponseWriter. ResponseController can be used to access the original http.ResponseWriter. See [https://go.dev/blog/go1.20]
func (*Response) WriteHeader ¶
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.
type Route ¶
type Route struct {
Method string
Path string
Name string
Handler HandlerFunc
Middlewares []MiddlewareFunc
}
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+Handler fields.
func (Route) ToRouteInfo ¶
ToRouteInfo converts Route to RouteInfo
func (Route) WithPrefix ¶
func (r Route) WithPrefix(pathPrefix string, middlewares []MiddlewareFunc) Route
WithPrefix recreates Route with added group prefix and group middlewares it is grouped to.
type Router ¶
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
}
Router is interface for routing request contexts to registered routes.
Contract between Echo/Context instance and the router:
- all routes must be added through methods on echo.Echo instance. Reason: Echo instance uses RouteInfo.Params() length to allocate slice for paths parameters (see `Echo.contextPathParamAllocSize`).
- 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
func NewConcurrentRouter ¶
NewConcurrentRouter creates concurrency safe Router which routes can be added/removed safely even after http.Server has been started.
type RouterConfig ¶
type RouterConfig struct {
NotFoundHandler HandlerFunc
MethodNotAllowedHandler HandlerFunc
OptionsMethodHandler HandlerFunc
AllowOverwritingRoute bool
UnescapePathParamValues bool
UseEscapedPathForMatching bool
}
RouterConfig is configuration options for (default) router
type Routes ¶
type Routes []RouteInfo
Routes is collection of RouteInfo instances with various helper methods.
func (Routes) FilterByMethod ¶
FilterByMethod searched for matching route info by method
func (Routes) FilterByName ¶
FilterByName searched for matching route info by name
func (Routes) FilterByPath ¶
FilterByPath searched for matching route info by path
func (Routes) FindByMethodPath ¶
FindByMethodPath searched for matching route info by method and path
type StartConfig ¶
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 *tls.Config
// ListenerNetwork is used configure on which Network listener will use.
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 `addres = ":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
}
StartConfig is for creating configured http.Server instance to start serve http(s) requests with given Echo instance
func (StartConfig) Start ¶
func (sc StartConfig) Start(ctx stdContext.Context, h http.Handler) error
Start starts given Handler with HTTP(s) server.
func (StartConfig) StartTLS ¶
func (sc StartConfig) StartTLS(ctx stdContext.Context, h http.Handler, certFile, keyFile any) error
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.
type TemplateRenderer ¶
type TemplateRenderer struct {
Template interface {
ExecuteTemplate(wr io.Writer, name string, data any) error
}
}
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 TimeLayout ¶
type TimeLayout string
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 TimeOpts ¶
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
}
TimeOpts is options for parsing time.Time values
type TrustOption ¶
type TrustOption func(*ipChecker)
TrustOption is config for which IP address to trust
func TrustIPRange ¶
func TrustIPRange(ipRange *net.IPNet) TrustOption
TrustIPRange add trustable IP ranges using CIDR notation.
func TrustLinkLocal ¶
func TrustLinkLocal(v bool) TrustOption
TrustLinkLocal configures if you trust link-local address (default: true).
func TrustLoopback ¶
func TrustLoopback(v bool) TrustOption
TrustLoopback configures if you trust loopback address (default: true).
func TrustPrivateNet ¶
func TrustPrivateNet(v bool) TrustOption
TrustPrivateNet configures if you trust private network address (default: true).
type ValueBinder ¶
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
}
ValueBinder provides utility methods for binding query or path parameter to various Go built-in types
func FormFieldBinder ¶
func FormFieldBinder(c *Context) *ValueBinder
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
func PathValuesBinder ¶
func PathValuesBinder(c *Context) *ValueBinder
PathValuesBinder creates path parameter value binder
func QueryParamsBinder ¶
func QueryParamsBinder(c *Context) *ValueBinder
QueryParamsBinder creates query parameter value binder
func (*ValueBinder) BindError ¶
func (b *ValueBinder) BindError() error
BindError returns first seen bind error and resets/empties binder errors for further calls
Example ¶
// example route function that binds query params to different destinations and stops binding on first bind error
failFastRouteFunc := func(c *echo.Context) error {
var opts struct {
IDs []int64
Active bool
}
length := int64(50) // default length is 50
// create binder that stops binding at first error
b := echo.QueryParamsBinder(c)
err := b.Int64("length", &length).
Int64s("ids", &opts.IDs).
Bool("active", &opts.Active).
BindError() // returns first binding error
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]
func (*ValueBinder) BindErrors ¶
func (b *ValueBinder) BindErrors() []error
BindErrors returns all bind errors and resets/empties binder errors for further calls
Example ¶
// example route function that binds query params to different destinations and returns all bind errors in one go
routeFunc := func(c *echo.Context) error {
var opts struct {
IDs []int64
Active bool
}
length := int64(50) // default length is 50
b := echo.QueryParamsBinder(c)
errs := b.Int64("length", &length).
Int64s("ids", &opts.IDs).
Bool("active", &opts.Active).
BindErrors() // returns all errors
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]
func (*ValueBinder) BindUnmarshaler ¶
func (b *ValueBinder) BindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder
BindUnmarshaler binds parameter to destination implementing BindUnmarshaler interface
func (*ValueBinder) BindWithDelimiter ¶
func (b *ValueBinder) BindWithDelimiter(sourceParam string, dest any, delimiter string) *ValueBinder
BindWithDelimiter binds parameter to destination by suitable conversion function. Delimiter is used before conversion to split parameter value to separate values
func (*ValueBinder) Bool ¶
func (b *ValueBinder) Bool(sourceParam string, dest *bool) *ValueBinder
Bool binds parameter to bool variable
func (*ValueBinder) Bools ¶
func (b *ValueBinder) Bools(sourceParam string, dest *[]bool) *ValueBinder
Bools binds parameter values to slice of bool variables
func (*ValueBinder) Byte ¶
func (b *ValueBinder) Byte(sourceParam string, dest *byte) *ValueBinder
Byte binds parameter to byte variable
func (*ValueBinder) CustomFunc ¶
func (b *ValueBinder) CustomFunc(sourceParam string, customFunc func(values []string) []error) *ValueBinder
CustomFunc binds parameter values with Func. Func is called only when parameter values exist.
Example ¶
// example route function that binds query params using custom function closure
routeFunc := func(c *echo.Context) error {
length := int64(50) // default length is 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 {
// in this example we use only first param value but url could contain multiple params in reality and
// therefore in theory produce multiple binding errors
return []error{echo.NewBindingError("base64", values[0:1], "failed to decode base64", err)}
}
binary = decoded
return nil
}).
BindErrors() // returns all errors
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 World
func (*ValueBinder) Duration ¶
func (b *ValueBinder) Duration(sourceParam string, dest *time.Duration) *ValueBinder
Duration binds parameter to time.Duration variable
func (*ValueBinder) Durations ¶
func (b *ValueBinder) Durations(sourceParam string, dest *[]time.Duration) *ValueBinder
Durations binds parameter values to slice of time.Duration variables
func (*ValueBinder) FailFast ¶
func (b *ValueBinder) FailFast(value bool) *ValueBinder
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
func (*ValueBinder) Float32 ¶
func (b *ValueBinder) Float32(sourceParam string, dest *float32) *ValueBinder
Float32 binds parameter to float32 variable
func (*ValueBinder) Float32s ¶
func (b *ValueBinder) Float32s(sourceParam string, dest *[]float32) *ValueBinder
Float32s binds parameter values to slice of float32 variables
func (*ValueBinder) Float64 ¶
func (b *ValueBinder) Float64(sourceParam string, dest *float64) *ValueBinder
Float64 binds parameter to float64 variable
func (*ValueBinder) Float64s ¶
func (b *ValueBinder) Float64s(sourceParam string, dest *[]float64) *ValueBinder
Float64s binds parameter values to slice of float64 variables
func (*ValueBinder) Int ¶
func (b *ValueBinder) Int(sourceParam string, dest *int) *ValueBinder
Int binds parameter to int variable
func (*ValueBinder) Int16 ¶
func (b *ValueBinder) Int16(sourceParam string, dest *int16) *ValueBinder
Int16 binds parameter to int16 variable
func (*ValueBinder) Int16s ¶
func (b *ValueBinder) Int16s(sourceParam string, dest *[]int16) *ValueBinder
Int16s binds parameter to slice of int16
func (*ValueBinder) Int32 ¶
func (b *ValueBinder) Int32(sourceParam string, dest *int32) *ValueBinder
Int32 binds parameter to int32 variable
func (*ValueBinder) Int32s ¶
func (b *ValueBinder) Int32s(sourceParam string, dest *[]int32) *ValueBinder
Int32s binds parameter to slice of int32
func (*ValueBinder) Int64 ¶
func (b *ValueBinder) Int64(sourceParam string, dest *int64) *ValueBinder
Int64 binds parameter to int64 variable
func (*ValueBinder) Int64s ¶
func (b *ValueBinder) Int64s(sourceParam string, dest *[]int64) *ValueBinder
Int64s binds parameter to slice of int64
func (*ValueBinder) Int8 ¶
func (b *ValueBinder) Int8(sourceParam string, dest *int8) *ValueBinder
Int8 binds parameter to int8 variable
func (*ValueBinder) Int8s ¶
func (b *ValueBinder) Int8s(sourceParam string, dest *[]int8) *ValueBinder
Int8s binds parameter to slice of int8
func (*ValueBinder) Ints ¶
func (b *ValueBinder) Ints(sourceParam string, dest *[]int) *ValueBinder
Ints binds parameter to slice of int
func (*ValueBinder) JSONUnmarshaler ¶
func (b *ValueBinder) JSONUnmarshaler(sourceParam string, dest json.Unmarshaler) *ValueBinder
JSONUnmarshaler binds parameter to destination implementing json.Unmarshaler interface
func (*ValueBinder) MustBindUnmarshaler ¶
func (b *ValueBinder) MustBindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder
MustBindUnmarshaler requires parameter value to exist to bind to destination implementing BindUnmarshaler interface. Returns error when value does not exist
func (*ValueBinder) MustBindWithDelimiter ¶
func (b *ValueBinder) MustBindWithDelimiter(sourceParam string, dest any, delimiter string) *ValueBinder
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
func (*ValueBinder) MustBool ¶
func (b *ValueBinder) MustBool(sourceParam string, dest *bool) *ValueBinder
MustBool requires parameter value to exist to bind to bool variable. Returns error when value does not exist
func (*ValueBinder) MustBools ¶
func (b *ValueBinder) MustBools(sourceParam string, dest *[]bool) *ValueBinder
MustBools requires parameter values to exist to bind to slice of bool variables. Returns error when values does not exist
func (*ValueBinder) MustByte ¶
func (b *ValueBinder) MustByte(sourceParam string, dest *byte) *ValueBinder
MustByte requires parameter value to exist to bind to byte variable. Returns error when value does not exist
func (*ValueBinder) MustCustomFunc ¶
func (b *ValueBinder) MustCustomFunc(sourceParam string, customFunc func(values []string) []error) *ValueBinder
MustCustomFunc requires parameter values to exist to bind with Func. Returns error when value does not exist.
func (*ValueBinder) MustDuration ¶
func (b *ValueBinder) MustDuration(sourceParam string, dest *time.Duration) *ValueBinder
MustDuration requires parameter value to exist to bind to time.Duration variable. Returns error when value does not exist
func (*ValueBinder) MustDurations ¶
func (b *ValueBinder) MustDurations(sourceParam string, dest *[]time.Duration) *ValueBinder
MustDurations requires parameter values to exist to bind to slice of time.Duration variables. Returns error when values does not exist
func (*ValueBinder) MustFloat32 ¶
func (b *ValueBinder) MustFloat32(sourceParam string, dest *float32) *ValueBinder
MustFloat32 requires parameter value to exist to bind to float32 variable. Returns error when value does not exist
func (*ValueBinder) MustFloat32s ¶
func (b *ValueBinder) MustFloat32s(sourceParam string, dest *[]float32) *ValueBinder
MustFloat32s requires parameter values to exist to bind to slice of float32 variables. Returns error when values does not exist
func (*ValueBinder) MustFloat64 ¶
func (b *ValueBinder) MustFloat64(sourceParam string, dest *float64) *ValueBinder
MustFloat64 requires parameter value to exist to bind to float64 variable. Returns error when value does not exist
func (*ValueBinder) MustFloat64s ¶
func (b *ValueBinder) MustFloat64s(sourceParam string, dest *[]float64) *ValueBinder
MustFloat64s requires parameter values to exist to bind to slice of float64 variables. Returns error when values does not exist
func (*ValueBinder) MustInt ¶
func (b *ValueBinder) MustInt(sourceParam string, dest *int) *ValueBinder
MustInt requires parameter value to exist to bind to int variable. Returns error when value does not exist
func (*ValueBinder) MustInt16 ¶
func (b *ValueBinder) MustInt16(sourceParam string, dest *int16) *ValueBinder
MustInt16 requires parameter value to exist to bind to int16 variable. Returns error when value does not exist
func (*ValueBinder) MustInt16s ¶
func (b *ValueBinder) MustInt16s(sourceParam string, dest *[]int16) *ValueBinder
MustInt16s requires parameter value to exist to bind to int16 slice variable. Returns error when value does not exist
func (*ValueBinder) MustInt32 ¶
func (b *ValueBinder) MustInt32(sourceParam string, dest *int32) *ValueBinder
MustInt32 requires parameter value to exist to bind to int32 variable. Returns error when value does not exist
func (*ValueBinder) MustInt32s ¶
func (b *ValueBinder) MustInt32s(sourceParam string, dest *[]int32) *ValueBinder
MustInt32s requires parameter value to exist to bind to int32 slice variable. Returns error when value does not exist
func (*ValueBinder) MustInt64 ¶
func (b *ValueBinder) MustInt64(sourceParam string, dest *int64) *ValueBinder
MustInt64 requires parameter value to exist to bind to int64 variable. Returns error when value does not exist
func (*ValueBinder) MustInt64s ¶
func (b *ValueBinder) MustInt64s(sourceParam string, dest *[]int64) *ValueBinder
MustInt64s requires parameter value to exist to bind to int64 slice variable. Returns error when value does not exist
func (*ValueBinder) MustInt8 ¶
func (b *ValueBinder) MustInt8(sourceParam string, dest *int8) *ValueBinder
MustInt8 requires parameter value to exist to bind to int8 variable. Returns error when value does not exist
func (*ValueBinder) MustInt8s ¶
func (b *ValueBinder) MustInt8s(sourceParam string, dest *[]int8) *ValueBinder
MustInt8s requires parameter value to exist to bind to int8 slice variable. Returns error when value does not exist
func (*ValueBinder) MustInts ¶
func (b *ValueBinder) MustInts(sourceParam string, dest *[]int) *ValueBinder
MustInts requires parameter value to exist to bind to int slice variable. Returns error when value does not exist
func (*ValueBinder) MustJSONUnmarshaler ¶
func (b *ValueBinder) MustJSONUnmarshaler(sourceParam string, dest json.Unmarshaler) *ValueBinder
MustJSONUnmarshaler requires parameter value to exist to bind to destination implementing json.Unmarshaler interface. Returns error when value does not exist
func (*ValueBinder) MustString ¶
func (b *ValueBinder) MustString(sourceParam string, dest *string) *ValueBinder
MustString requires parameter value to exist to bind to string variable. Returns error when value does not exist
func (*ValueBinder) MustStrings ¶
func (b *ValueBinder) MustStrings(sourceParam string, dest *[]string) *ValueBinder
MustStrings requires parameter values to exist to bind to slice of string variables. Returns error when value does not exist
func (*ValueBinder) MustTextUnmarshaler ¶
func (b *ValueBinder) MustTextUnmarshaler(sourceParam string, dest encoding.TextUnmarshaler) *ValueBinder
MustTextUnmarshaler requires parameter value to exist to bind to destination implementing encoding.TextUnmarshaler interface. Returns error when value does not exist
func (*ValueBinder) MustTime ¶
func (b *ValueBinder) MustTime(sourceParam string, dest *time.Time, layout string) *ValueBinder
MustTime requires parameter value to exist to bind to time.Time variable. Returns error when value does not exist
func (*ValueBinder) MustTimes ¶
func (b *ValueBinder) MustTimes(sourceParam string, dest *[]time.Time, layout string) *ValueBinder
MustTimes requires parameter values to exist to bind to slice of time.Time variables. Returns error when values does not exist
func (*ValueBinder) MustUint ¶
func (b *ValueBinder) MustUint(sourceParam string, dest *uint) *ValueBinder
MustUint requires parameter value to exist to bind to uint variable. Returns error when value does not exist
func (*ValueBinder) MustUint16 ¶
func (b *ValueBinder) MustUint16(sourceParam string, dest *uint16) *ValueBinder
MustUint16 requires parameter value to exist to bind to uint16 variable. Returns error when value does not exist
func (*ValueBinder) MustUint16s ¶
func (b *ValueBinder) MustUint16s(sourceParam string, dest *[]uint16) *ValueBinder
MustUint16s requires parameter value to exist to bind to uint16 slice variable. Returns error when value does not exist
func (*ValueBinder) MustUint32 ¶
func (b *ValueBinder) MustUint32(sourceParam string, dest *uint32) *ValueBinder
MustUint32 requires parameter value to exist to bind to uint32 variable. Returns error when value does not exist
func (*ValueBinder) MustUint32s ¶
func (b *ValueBinder) MustUint32s(sourceParam string, dest *[]uint32) *ValueBinder
MustUint32s requires parameter value to exist to bind to uint32 slice variable. Returns error when value does not exist
func (*ValueBinder) MustUint64 ¶
func (b *ValueBinder) MustUint64(sourceParam string, dest *uint64) *ValueBinder
MustUint64 requires parameter value to exist to bind to uint64 variable. Returns error when value does not exist
func (*ValueBinder) MustUint64s ¶
func (b *ValueBinder) MustUint64s(sourceParam string, dest *[]uint64) *ValueBinder
MustUint64s requires parameter value to exist to bind to uint64 slice variable. Returns error when value does not exist
func (*ValueBinder) MustUint8 ¶
func (b *ValueBinder) MustUint8(sourceParam string, dest *uint8) *ValueBinder
MustUint8 requires parameter value to exist to bind to uint8 variable. Returns error when value does not exist
func (*ValueBinder) MustUint8s ¶
func (b *ValueBinder) MustUint8s(sourceParam string, dest *[]uint8) *ValueBinder
MustUint8s requires parameter value to exist to bind to uint8 slice variable. Returns error when value does not exist
func (*ValueBinder) MustUints ¶
func (b *ValueBinder) MustUints(sourceParam string, dest *[]uint) *ValueBinder
MustUints requires parameter value to exist to bind to uint slice variable. Returns error when value does not exist
func (*ValueBinder) MustUnixTime ¶
func (b *ValueBinder) MustUnixTime(sourceParam string, dest *time.Time) *ValueBinder
MustUnixTime requires parameter value to exist to bind to time.Duration 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:
- time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal
func (*ValueBinder) MustUnixTimeMilli ¶
func (b *ValueBinder) MustUnixTimeMilli(sourceParam string, dest *time.Time) *ValueBinder
MustUnixTimeMilli requires parameter value to exist to bind to time.Duration 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:
- time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal
func (*ValueBinder) MustUnixTimeNano ¶
func (b *ValueBinder) MustUnixTimeNano(sourceParam string, dest *time.Time) *ValueBinder
MustUnixTimeNano requires parameter value to exist to bind to time.Duration variable (in local Time corresponding to the given Unix time value in nano second 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:
- time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal
- Javascript's Number type only has about 53 bits of precision (Number.MAX_SAFE_INTEGER = 9007199254740991). Compare it to 1609180603123456789 in example.
func (*ValueBinder) String ¶
func (b *ValueBinder) String(sourceParam string, dest *string) *ValueBinder
String binds parameter to string variable
func (*ValueBinder) Strings ¶
func (b *ValueBinder) Strings(sourceParam string, dest *[]string) *ValueBinder
Strings binds parameter values to slice of string
func (*ValueBinder) TextUnmarshaler ¶
func (b *ValueBinder) TextUnmarshaler(sourceParam string, dest encoding.TextUnmarshaler) *ValueBinder
TextUnmarshaler binds parameter to destination implementing encoding.TextUnmarshaler interface
func (*ValueBinder) Time ¶
func (b *ValueBinder) Time(sourceParam string, dest *time.Time, layout string) *ValueBinder
Time binds parameter to time.Time variable
func (*ValueBinder) Times ¶
func (b *ValueBinder) Times(sourceParam string, dest *[]time.Time, layout string) *ValueBinder
Times binds parameter values to slice of time.Time variables
func (*ValueBinder) Uint ¶
func (b *ValueBinder) Uint(sourceParam string, dest *uint) *ValueBinder
Uint binds parameter to uint variable
func (*ValueBinder) Uint16 ¶
func (b *ValueBinder) Uint16(sourceParam string, dest *uint16) *ValueBinder
Uint16 binds parameter to uint16 variable
func (*ValueBinder) Uint16s ¶
func (b *ValueBinder) Uint16s(sourceParam string, dest *[]uint16) *ValueBinder
Uint16s binds parameter to slice of uint16
func (*ValueBinder) Uint32 ¶
func (b *ValueBinder) Uint32(sourceParam string, dest *uint32) *ValueBinder
Uint32 binds parameter to uint32 variable
func (*ValueBinder) Uint32s ¶
func (b *ValueBinder) Uint32s(sourceParam string, dest *[]uint32) *ValueBinder
Uint32s binds parameter to slice of uint32
func (*ValueBinder) Uint64 ¶
func (b *ValueBinder) Uint64(sourceParam string, dest *uint64) *ValueBinder
Uint64 binds parameter to uint64 variable
func (*ValueBinder) Uint64s ¶
func (b *ValueBinder) Uint64s(sourceParam string, dest *[]uint64) *ValueBinder
Uint64s binds parameter to slice of uint64
func (*ValueBinder) Uint8 ¶
func (b *ValueBinder) Uint8(sourceParam string, dest *uint8) *ValueBinder
Uint8 binds parameter to uint8 variable
func (*ValueBinder) Uint8s ¶
func (b *ValueBinder) Uint8s(sourceParam string, dest *[]uint8) *ValueBinder
Uint8s binds parameter to slice of uint8
func (*ValueBinder) Uints ¶
func (b *ValueBinder) Uints(sourceParam string, dest *[]uint) *ValueBinder
Uints binds parameter to slice of uint
func (*ValueBinder) UnixTime ¶
func (b *ValueBinder) UnixTime(sourceParam string, dest *time.Time) *ValueBinder
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:
- time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal
func (*ValueBinder) UnixTimeMilli ¶
func (b *ValueBinder) UnixTimeMilli(sourceParam string, dest *time.Time) *ValueBinder
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:
- time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal
func (*ValueBinder) UnixTimeNano ¶
func (b *ValueBinder) UnixTimeNano(sourceParam string, dest *time.Time) *ValueBinder
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:
- time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal
- Javascript's Number type only has about 53 bits of precision (Number.MAX_SAFE_INTEGER = 9007199254740991). Compare it to 1609180603123456789 in example.