echo

package module
v4.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 17, 2023 License: MIT Imports: 30 Imported by: 1

README

Sourcegraph GoDoc Go Report Card Build Status Codecov Forum Twitter License

Supported Go versions

Latest version of Echo supports last four Go major releases and might work with older versions.

As of version 4.0.0, Echo is available as a Go module. Therefore a Go version capable of understanding /vN suffixed imports is required:

Any of these versions will allow you to import Echo as github.com/labstack/echo/v4 which is the recommended way of using Echo going forward.

For older versions, please use the latest v3 tag.

Feature Overview

  • Optimized HTTP router which smartly prioritize routes
  • Build robust and scalable RESTful APIs
  • Group APIs
  • Extensible middleware framework
  • Define middleware at root, group or route level
  • Data binding for JSON, XML and form payload
  • Handy functions to send variety of HTTP responses
  • Centralized HTTP error handling
  • Template rendering with any template engine
  • Define your format for the logger
  • Highly customizable
  • Automatic TLS via Let’s Encrypt
  • HTTP/2 support

Benchmarks

Date: 2020/11/11
Source: https://github.com/vishr/web-framework-benchmark
Lower is better!

The benchmarks above were run on an Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz

Guide

Installation

// go get github.com/labstack/echo/{version}
go get github.com/labstack/echo/v4

Example

package main

import (
  "github.com/labstack/echo/v4"
  "github.com/labstack/echo/v4/middleware"
  "net/http"
)

func main() {
  // Echo instance
  e := echo.New()

  // Middleware
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())

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

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

// Handler
func hello(c echo.Context) error {
  return c.String(http.StatusOK, "Hello, World!")
}

Official middleware repositories

Following list of middleware is maintained by Echo team.

Repository Description
github.com/labstack/echo-jwt JWT middleware
github.com/labstack/echo-contrib casbin, gorilla/sessions, jaegertracing, prometheus, pprof, zipkin middlewares

Third-party middleware repositories

Be careful when adding 3rd party middleware. Echo teams does not have time or manpower to guarantee safety and quality of middlewares in this list.

Repository Description
deepmap/oapi-codegen Automatically generate RESTful API documentation with OpenAPI Client and Server Code Generator
github.com/swaggo/echo-swagger Automatically generate RESTful API documentation with Swagger 2.0.
github.com/ziflex/lecho Zerolog logging library wrapper for Echo logger interface.
github.com/brpaz/echozap Uber´s Zap logging library wrapper for Echo logger interface.
github.com/darkweak/souin/plugins/echo HTTP cache system based on Souin to automatically get your endpoints cached. It supports some distributed and non-distributed storage systems depending your needs.
github.com/mikestefanello/pagoda Rapid, easy full-stack web development starter kit built with Echo.
github.com/go-woo/protoc-gen-echo ProtoBuf generate Echo server side code

Please send a PR to add your own library here.

Help

Contribute

Use issues for everything

  • For a small change, just send a PR.
  • For bigger changes open an issue for discussion before sending a PR.
  • PR should have:
    • Test case
    • Documentation
    • Example (If it makes sense)
  • You can also contribute by:
    • Reporting issues
    • Suggesting new features or enhancements
    • Improve/fix documentation

Credits

License

MIT

Documentation

Overview

Package echo implements high performance, minimalist Go web framework.

Example:

package main

import (
  "net/http"

  "github.com/labstack/echo/v4"
  "github.com/labstack/echo/v4/middleware"
)

// Handler
func hello(c echo.Context) error {
  return c.String(http.StatusOK, "Hello, World!")
}

func main() {
  // Echo instance
  e := echo.New()

  // Middleware
  e.Use(middleware.Logger())
  e.Use(middleware.Recover())

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

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

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

Index

Examples

Constants

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

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

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	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

View Source
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"
)
View Source
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              = "Origin"
	HeaderCacheControl        = "Cache-Control"
	HeaderConnection          = "Connection"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
)

Headers

View Source
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"
)
View Source
const (
	// Version of Echo
	Version = "4.10.2"
)

Variables

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

	ErrValidatorNotRegistered = errors.New("validator not registered")
	ErrRendererNotRegistered  = errors.New("renderer not registered")
	ErrInvalidRedirectCode    = errors.New("invalid redirect status code")
	ErrCookieNotFound         = errors.New("cookie not found")
	ErrInvalidCertOrKeyType   = errors.New("invalid cert or key type, must be string or []byte")
	ErrInvalidListenerNetwork = errors.New("invalid listener network")
)

Errors

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

	MethodNotAllowedHandler = func(c Context) error {

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

Error handlers

Functions

func GetPath

func GetPath(r *http.Request) string

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

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

func MustSubFS

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

MustSubFS creates sub FS from current filesystem or panic on failure. Panic happens when `fsRoot` contains invalid path according to `fs.ValidPath` rules.

MustSubFS is helpful when dealing with `embed.FS` because for example `//go:embed assets/images` embeds files with paths including `assets/images` as their prefix. In that case use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary prefix for directory path.

func NewBindingError

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

NewBindingError creates new instance of binding error

Types

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 Binder

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

Binder is the interface that wraps the Bind method.

type BindingError

type BindingError struct {
	// Field is the field name where value binding failed
	Field string `json:"field"`
	// Values of parameter that failed to bind.
	Values []string `json:"-"`
	*HTTPError
}

BindingError represents an error that occurred while binding request data.

func (*BindingError) Error

func (be *BindingError) Error() string

Error returns error message

type Context

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

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

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

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

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

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

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

	// RealIP returns the client's network address based on `X-Forwarded-For`
	// or `X-Real-IP` request header.
	// The behavior can be configured using `Echo#IPExtractor`.
	RealIP() string

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// Get retrieves data from the context.
	Get(key string) interface{}

	// Set saves data in the context.
	Set(key string, val interface{})

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

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

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

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

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

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

	// JSON sends a JSON response with status code.
	JSON(code int, i interface{}) error

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

	//JSON, but don't encode html chars
	JSONNonEncodePretty(code int, i interface{}, indent string) error

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

	// JSONP sends a JSONP response with status code. It uses `callback` to construct
	// the JSONP payload.
	JSONP(code int, callback string, i interface{}) error

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

	// XML sends an XML response with status code.
	XML(code int, i interface{}) error

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

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

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

	// DownloadBlob sends a blob response as attachement.
	DownloadBlob(contentType, fileName string, b []byte) error

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

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

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

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

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

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

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

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

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

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

	// SetLogger Set the logger
	SetLogger(l Logger)

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

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

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

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

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

Bind implements the `Binder#Bind` function. Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous step binded values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams.

func (*DefaultBinder) BindBody

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

BindBody binds request body contents to bindable object NB: then binding forms take note that this implementation uses standard library form parsing which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm

func (*DefaultBinder) BindHeaders

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

BindHeaders binds HTTP headers to a bindable object

func (*DefaultBinder) BindPathParams

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

BindPathParams binds path params to bindable object

func (*DefaultBinder) BindQueryParams

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

BindQueryParams binds query params to bindable object

type DefaultJSONSerializer

type DefaultJSONSerializer struct{}

DefaultJSONSerializer implements JSON encoding using encoding/json.

func (DefaultJSONSerializer) Deserialize

func (d DefaultJSONSerializer) Deserialize(c Context, i interface{}) error

Deserialize reads a JSON from a request body and converts it into an interface.

func (DefaultJSONSerializer) NonEscapeSerialize

func (d DefaultJSONSerializer) NonEscapeSerialize(c Context, i interface{}, indent string) error

Alt non-escaping serializer

func (DefaultJSONSerializer) Serialize

func (d DefaultJSONSerializer) Serialize(c Context, i interface{}, indent string) error

Serialize converts an interface into a json and writes it to the response. You can optionally use the indent parameter to produce pretty JSONs.

type Echo

type Echo struct {
	StdLogger        *stdLog.Logger
	Server           *http.Server
	TLSServer        *http.Server
	Listener         net.Listener
	TLSListener      net.Listener
	AutoTLSManager   autocert.Manager
	DisableHTTP2     bool
	Debug            bool
	HideBanner       bool
	HidePort         bool
	HTTPErrorHandler HTTPErrorHandler
	Binder           Binder
	JSONSerializer   JSONSerializer
	Validator        Validator
	Renderer         Renderer
	Logger           Logger
	IPExtractor      IPExtractor
	ListenerNetwork  string

	// OnAddRouteHandler is called when Echo adds new route to specific host router.
	OnAddRouteHandler func(host string, route Route, handler HandlerFunc, middleware []MiddlewareFunc)
	// 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. Adding new routes after the server has been started is also not safe!

func New

func New() (e *Echo)

New creates an instance of Echo.

func (*Echo) AcquireContext

func (e *Echo) AcquireContext() Context

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) *Route

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) []*Route

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) *Route

CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) Close

func (e *Echo) Close() error

Close immediately stops the server. It internally calls `http.Server#Close()`.

func (*Echo) DELETE

func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

DELETE registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) DefaultHTTPErrorHandler

func (e *Echo) DefaultHTTPErrorHandler(err error, c Context)

DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response with status code.

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 "commited" the response and status code header has been sent to the client.

func (*Echo) File

func (e *Echo) File(path, file string, m ...MiddlewareFunc) *Route

File registers a new route with path to serve a static file with optional route-level middleware.

func (*Echo) FileFS

func (e *Echo) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) *Route

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) *Route

GET registers a new GET route for a path with matching handler in the router with optional route-level middleware.

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) *Route

HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) Host

func (e *Echo) Host(name string, m ...MiddlewareFunc) (g *Group)

Host creates a new router group for the provided host and optional host-level middleware.

func (*Echo) ListenerAddr

func (e *Echo) ListenerAddr() net.Addr

ListenerAddr returns net.Addr for Listener

func (*Echo) Match

func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.

func (*Echo) NewContext

func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context

NewContext returns a Context instance.

func (*Echo) OPTIONS

func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

OPTIONS registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) PATCH

func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PATCH registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) POST

func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

POST registers a new POST route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) PUT

func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PUT registers a new PUT route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) Pre

func (e *Echo) Pre(middleware ...MiddlewareFunc)

Pre adds middleware to the chain which is run before router.

func (*Echo) ReleaseContext

func (e *Echo) ReleaseContext(c Context)

ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.

func (*Echo) Reverse

func (e *Echo) Reverse(name string, params ...interface{}) string

Reverse generates an URL from route name and provided parameters.

func (*Echo) RouteNotFound

func (e *Echo) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

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

func (e *Echo) Router() *Router

Router returns the default router.

func (*Echo) Routers

func (e *Echo) Routers() map[string]*Router

Routers returns the map of host => router.

func (*Echo) Routes

func (e *Echo) Routes() []*Route

Routes returns the registered routes for default router. In case when Echo serves multiple hosts/domains use `e.Routers()["domain2.site"].Routes()` to get specific host routes.

func (*Echo) ServeHTTP

func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements `http.Handler` interface, which serves HTTP requests.

func (*Echo) Shutdown

func (e *Echo) Shutdown(ctx stdContext.Context) error

Shutdown stops the server gracefully. It internally calls `http.Server#Shutdown()`.

func (*Echo) Start

func (e *Echo) Start(address string) error

Start starts an HTTP server.

func (*Echo) StartAutoTLS

func (e *Echo) StartAutoTLS(address string) error

StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.

func (*Echo) StartH2CServer

func (e *Echo) StartH2CServer(address string, h2s *http2.Server) error

StartH2CServer starts a custom http/2 server with h2c (HTTP/2 Cleartext).

func (*Echo) StartServer

func (e *Echo) StartServer(s *http.Server) (err error)

StartServer starts a custom http server.

func (*Echo) StartTLS

func (e *Echo) StartTLS(address string, certFile, keyFile interface{}) (err error)

StartTLS starts an 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.

func (*Echo) Static

func (e *Echo) Static(pathPrefix, fsRoot string) *Route

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) *Route

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

func (e *Echo) TLSListenerAddr() net.Addr

TLSListenerAddr returns net.Addr for TLSListener

func (*Echo) TRACE

func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.

func (*Echo) URI

func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string

URI generates an URI from handler.

func (*Echo) URL

func (e *Echo) URL(h HandlerFunc, params ...interface{}) string

URL is an alias for `URI` function.

func (*Echo) Use

func (e *Echo) Use(middleware ...MiddlewareFunc)

Use adds middleware to the chain which is run after router.

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) *Route

Add implements `Echo#Add()` for sub-routes within the Group.

func (*Group) Any

func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Any implements `Echo#Any()` for sub-routes within the Group.

func (*Group) CONNECT

func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

CONNECT implements `Echo#CONNECT()` for sub-routes within the Group.

func (*Group) DELETE

func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

DELETE implements `Echo#DELETE()` for sub-routes within the Group.

func (*Group) File

func (g *Group) File(path, file string)

File implements `Echo#File()` for sub-routes within the Group.

func (*Group) FileFS

func (g *Group) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) *Route

FileFS implements `Echo#FileFS()` for sub-routes within the Group.

func (*Group) GET

func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

GET implements `Echo#GET()` for sub-routes within the Group.

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.

func (*Group) HEAD

func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

HEAD implements `Echo#HEAD()` for sub-routes within the Group.

func (*Group) Match

func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Match implements `Echo#Match()` for sub-routes within the Group.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group.

func (*Group) PATCH

func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PATCH implements `Echo#PATCH()` for sub-routes within the Group.

func (*Group) POST

func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

POST implements `Echo#POST()` for sub-routes within the Group.

func (*Group) PUT

func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PUT implements `Echo#PUT()` for sub-routes within the Group.

func (*Group) RouteNotFound

func (g *Group) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

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)

Static implements `Echo#Static()` for sub-routes within the Group.

func (*Group) StaticFS

func (g *Group) StaticFS(pathPrefix string, filesystem fs.FS)

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) *Route

TRACE implements `Echo#TRACE()` for sub-routes within the Group.

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc)

Use implements `Echo#Use()` for sub-routes within the Group.

type HTTPError

type HTTPError struct {
	Code     int         `json:"-"`
	Message  interface{} `json:"message"`
	Internal error       `json:"-"` // Stores the error returned by an external dependency
}

HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(code int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error makes it compatible with `error` interface.

func (*HTTPError) SetInternal

func (he *HTTPError) SetInternal(err error) *HTTPError

SetInternal sets error to HTTPError.Internal

func (*HTTPError) Unwrap

func (he *HTTPError) Unwrap() error

Unwrap satisfies the Go 1.13 error wrapper interface.

func (*HTTPError) WithInternal

func (he *HTTPError) WithInternal(err error) *HTTPError

WithInternal returns clone of HTTPError with err set to HTTPError.Internal field

type HTTPErrorHandler

type HTTPErrorHandler func(err error, c Context)

HTTPErrorHandler is a centralized HTTP error handler.

type HandlerFunc

type HandlerFunc func(c Context) error

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

type IPExtractor func(*http.Request) string

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, i interface{}, indent string) error
	NonEscapeSerialize(c Context, i interface{}, indent string) error
	Deserialize(c Context, i interface{}) error
}

JSONSerializer is the interface that encodes and decodes JSON to and from interfaces.

type Logger

type Logger interface {
	Output() io.Writer
	SetOutput(w io.Writer)
	Prefix() string
	SetPrefix(p string)
	Level() log.Lvl
	SetLevel(v log.Lvl)
	SetHeader(h string)
	Print(i ...interface{})
	Printf(format string, args ...interface{})
	Printj(j log.JSON)
	Debug(i ...interface{})
	Debugf(format string, args ...interface{})
	Debugj(j log.JSON)
	Info(i ...interface{})
	Infof(format string, args ...interface{})
	Infoj(j log.JSON)
	Warn(i ...interface{})
	Warnf(format string, args ...interface{})
	Warnj(j log.JSON)
	Error(i ...interface{})
	Errorf(format string, args ...interface{})
	Errorj(j log.JSON)
	Fatal(i ...interface{})
	Fatalj(j log.JSON)
	Fatalf(format string, args ...interface{})
	Panic(i ...interface{})
	Panicj(j log.JSON)
	Panicf(format string, args ...interface{})
}

Logger defines the logging interface.

type Map

type Map map[string]interface{}

Map defines a generic map of type `map[string]interface{}`.

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 Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}, Context) error
}

Renderer is the interface that wraps the Render function.

type Response

type Response struct {
	Writer    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, e *Echo) (r *Response)

NewResponse creates a new instance of Response.

func (*Response) After

func (r *Response) After(fn func())

After registers a function which is called just after the response is written. If the `Content-Length` is unknown, none of the after function is executed.

func (*Response) Before

func (r *Response) Before(fn func())

Before registers a function which is called just before the response 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) Header

func (r *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

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 `json:"method"`
	Path   string `json:"path"`
	Name   string `json:"name"`
}

Route contains a handler and information for matching against requests.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router is the registry of all registered routes for an `Echo` instance for request matching and URL path parameter parsing.

func NewRouter

func NewRouter(e *Echo) *Router

NewRouter returns a new Router instance.

func (*Router) Add

func (r *Router) Add(method, path string, h HandlerFunc)

Add registers a new route for method and path with matching handler.

func (*Router) Find

func (r *Router) Find(method, path string, c Context)

Find lookup a handler registered for method and path. It also parses URL for path parameters and load them into context.

For performance:

- Get context from `Echo#AcquireContext()` - Reset it `Context#Reset()` - Return it `Echo#ReleaseContext()`.

func (*Router) Reverse

func (r *Router) Reverse(name string, params ...interface{}) string

Reverse generates an URL from route name and provided parameters.

func (*Router) Routes

func (r *Router) Routes() []*Route

Routes returns the registered routes.

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 Validator

type Validator interface {
	Validate(i interface{}) error
}

Validator is the interface that wraps the Validate function.

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 interface{}, 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 PathParamsBinder

func PathParamsBinder(c Context) *ValueBinder

PathParamsBinder 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 {
		Active bool
		IDs    []int64
	}
	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 {
		Active bool
		IDs    []int64
	}
	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 interface{}, 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 interface{}, 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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL