echo package - github.com/labstack/echo/v4 - Go Packages (original) (raw)

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

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

View Source

const (

MIMEApplicationJSON = "application/json"


MIMEApplicationJSONCharsetUTF8       = [MIMEApplicationJSON](#MIMEApplicationJSON) + "; " + charsetUTF8
MIMEApplicationJavaScript            = "application/javascript"
MIMEApplicationJavaScriptCharsetUTF8 = [MIMEApplicationJavaScript](#MIMEApplicationJavaScript) + "; " + charsetUTF8
MIMEApplicationXML                   = "application/xml"
MIMEApplicationXMLCharsetUTF8        = [MIMEApplicationXML](#MIMEApplicationXML) + "; " + charsetUTF8
MIMETextXML                          = "text/xml"
MIMETextXMLCharsetUTF8               = [MIMETextXML](#MIMETextXML) + "; " + charsetUTF8
MIMEApplicationForm                  = "application/x-www-form-urlencoded"
MIMEApplicationProtobuf              = "application/protobuf"
MIMEApplicationMsgpack               = "application/msgpack"
MIMETextHTML                         = "text/html"
MIMETextHTMLCharsetUTF8              = [MIMETextHTML](#MIMETextHTML) + "; " + charsetUTF8
MIMETextPlain                        = "text/plain"
MIMETextPlainCharsetUTF8             = [MIMETextPlain](#MIMETextPlain) + "; " + charsetUTF8
MIMEMultipartForm                    = "multipart/form-data"
MIMEOctetStream                      = "application/octet-stream"

)

MIME types

View Source

const (

PROPFIND = "PROPFIND"

REPORT = "REPORT"

RouteNotFound = "echo_route_not_found"

)

View Source

const (

HeaderContentDisposition  = "Content-Disposition"
HeaderContentEncoding     = "Content-Encoding"
HeaderContentLength       = "Content-Length"
HeaderContentType         = "Content-Type"


HeaderXContentTypeOptions             = "X-Content-Type-Options"
HeaderContentSecurityPolicy           = "Content-Security-Policy"
HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"

)

Headers

View Source

const (

ContextKeyHeaderAllow = "echo_header_allow"

)

Errors

View Source

var MethodNotAllowedHandler = func(c Context) error {

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

}

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

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

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

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

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

NewBindingError creates new instance of binding error

type BindUnmarshaler interface {

UnmarshalParam(param [string](/builtin#string)) [error](/builtin#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 interface { Bind(i interface{}, c Context) error }

Binder is the interface that wraps the Bind method.

type BindingError struct {

Field [string](/builtin#string) `json:"field"`
*[HTTPError](#HTTPError)

Values [][string](/builtin#string) `json:"-"`

}

BindingError represents an error that occurred while binding request data.

Error returns error message

type Context interface {

Request() *[http](/net/http).[Request](/net/http#Request)


SetRequest(r *[http](/net/http).[Request](/net/http#Request))


SetResponse(r *[Response](#Response))


Response() *[Response](#Response)


IsTLS() [bool](/builtin#bool)


IsWebSocket() [bool](/builtin#bool)


Scheme() [string](/builtin#string)


RealIP() [string](/builtin#string)


Path() [string](/builtin#string)


SetPath(p [string](/builtin#string))


Param(name [string](/builtin#string)) [string](/builtin#string)


ParamNames() [][string](/builtin#string)


SetParamNames(names ...[string](/builtin#string))


ParamValues() [][string](/builtin#string)


SetParamValues(values ...[string](/builtin#string))


QueryParam(name [string](/builtin#string)) [string](/builtin#string)


QueryParams() [url](/net/url).[Values](/net/url#Values)


QueryString() [string](/builtin#string)


FormValue(name [string](/builtin#string)) [string](/builtin#string)


FormParams() ([url](/net/url).[Values](/net/url#Values), [error](/builtin#error))


FormFile(name [string](/builtin#string)) (*[multipart](/mime/multipart).[FileHeader](/mime/multipart#FileHeader), [error](/builtin#error))


MultipartForm() (*[multipart](/mime/multipart).[Form](/mime/multipart#Form), [error](/builtin#error))


Cookie(name [string](/builtin#string)) (*[http](/net/http).[Cookie](/net/http#Cookie), [error](/builtin#error))


SetCookie(cookie *[http](/net/http).[Cookie](/net/http#Cookie))


Cookies() []*[http](/net/http).[Cookie](/net/http#Cookie)


Get(key [string](/builtin#string)) [any](/builtin#any)


Set(key [string](/builtin#string), val [any](/builtin#any))


Bind(i [any](/builtin#any)) [error](/builtin#error)


Validate(i [any](/builtin#any)) [error](/builtin#error)


Render(code [int](/builtin#int), name [string](/builtin#string), data [any](/builtin#any)) [error](/builtin#error)


HTML(code [int](/builtin#int), html [string](/builtin#string)) [error](/builtin#error)


HTMLBlob(code [int](/builtin#int), b [][byte](/builtin#byte)) [error](/builtin#error)


String(code [int](/builtin#int), s [string](/builtin#string)) [error](/builtin#error)


JSON(code [int](/builtin#int), i [any](/builtin#any)) [error](/builtin#error)


JSONPretty(code [int](/builtin#int), i [any](/builtin#any), indent [string](/builtin#string)) [error](/builtin#error)


JSONBlob(code [int](/builtin#int), b [][byte](/builtin#byte)) [error](/builtin#error)


JSONP(code [int](/builtin#int), callback [string](/builtin#string), i [any](/builtin#any)) [error](/builtin#error)


JSONPBlob(code [int](/builtin#int), callback [string](/builtin#string), b [][byte](/builtin#byte)) [error](/builtin#error)


XML(code [int](/builtin#int), i [any](/builtin#any)) [error](/builtin#error)


XMLPretty(code [int](/builtin#int), i [any](/builtin#any), indent [string](/builtin#string)) [error](/builtin#error)


XMLBlob(code [int](/builtin#int), b [][byte](/builtin#byte)) [error](/builtin#error)


Blob(code [int](/builtin#int), contentType [string](/builtin#string), b [][byte](/builtin#byte)) [error](/builtin#error)


Stream(code [int](/builtin#int), contentType [string](/builtin#string), r [io](/io).[Reader](/io#Reader)) [error](/builtin#error)


File(file [string](/builtin#string)) [error](/builtin#error)


Attachment(file [string](/builtin#string), name [string](/builtin#string)) [error](/builtin#error)


Inline(file [string](/builtin#string), name [string](/builtin#string)) [error](/builtin#error)


NoContent(code [int](/builtin#int)) [error](/builtin#error)


Redirect(code [int](/builtin#int), url [string](/builtin#string)) [error](/builtin#error)


Error(err [error](/builtin#error))


Handler() [HandlerFunc](#HandlerFunc)


SetHandler(h [HandlerFunc](#HandlerFunc))


Logger() [Logger](#Logger)


SetLogger(l [Logger](#Logger))


Echo() *[Echo](#Echo)


Reset(r *[http](/net/http).[Request](/net/http#Request), w [http](/net/http).[ResponseWriter](/net/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 struct{}

DefaultBinder is the default implementation of the Binder interface.

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 (b *DefaultBinder) BindHeaders(c Context, i interface{}) error

BindHeaders binds HTTP headers to a bindable object

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

BindPathParams binds path params to bindable object

Time format support: time.Time fields can use `format` tags to specify custom parsing layouts. Example: `param:"created" format:"2006-01-02T15:04"` for datetime-local format Example: `param:"date" format:"2006-01-02"` for date format Uses Go's standard time format reference time: Mon Jan 2 15:04:05 MST 2006 Works with form data, query parameters, and path parameters (not JSON body) Falls back to default time.Time parsing if no format tag is specified

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

BindQueryParams binds query params to bindable object

type DefaultJSONSerializer struct{}

DefaultJSONSerializer implements JSON encoding using encoding/json.

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

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

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

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!

New creates an instance of Echo.

func (e *Echo) AcquireContext() Context

AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.

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 (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.

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

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

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

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 (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.

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

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

Group creates a new router group with prefix and optional group-level middleware.

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

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

ListenerAddr returns net.Addr for Listener

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.

NewContext returns a Context instance.

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

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

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

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

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

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

func (e *Echo) ReleaseContext(c Context)

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

Reverse generates a URL from route name and provided parameters.

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 (e *Echo) Router() *Router

Router returns the default router.

Routers returns the map of host => router.

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.

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

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

Start starts an HTTP server.

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

StartServer starts a custom http server.

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 (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 (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 (e *Echo) TLSListenerAddr() net.Addr

TLSListenerAddr returns net.Addr for TLSListener

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

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

URI generates an URI from handler.

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

URL is an alias for `URI` function.

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

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

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 (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

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

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

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

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

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

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

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

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

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

GET implements `Echo#GET()` for sub-routes within the 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.

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

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

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

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

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

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

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 (g *Group) Static(pathPrefix, fsRoot string)

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

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.

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

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

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

type HTTPError struct { Internal error json:"-" Message interface{} json:"message" Code int json:"-" }

HTTPError represents an error that occurred while handling a request.

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

NewHTTPError creates a new HTTPError instance.

Error makes it compatible with `error` interface.

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

SetInternal sets error to HTTPError.Internal

Unwrap satisfies the Go 1.13 error wrapper interface.

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 added in v4.7.0

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 added in v4.7.0

StaticFileHandler creates handler function to serve file from provided file system

func WrapHandler

WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.

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() 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(options ...TrustOption) IPExtractor

ExtractIPFromRealIPHeader extracts IP address using x-real-ip header. Use this if you put proxy which uses this header.

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 interface { Serialize(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 interface { Output() io.Writer SetOutput(w io.Writer) Prefix() string SetPrefix(p string) Level() log.Lvl SetLevel(v log.Lvl) 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 map[string]interface{}

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

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc defines a function to process middleware.

WrapMiddleware wraps `func(http.Handler) http.Handler` into `echo.MiddlewareFunc`

Renderer is the interface that wraps the Render function.

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

NewResponse creates a new instance of Response.

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 (r *Response) Before(fn func())

Before registers a function which is called just before the response is written.

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

Unwrap returns the original http.ResponseWriter. ResponseController can be used to access the original http.ResponseWriter. See [https://go.dev/blog/go1.20]

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

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

Route contains a handler and information for matching against requests.

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

func NewRouter(e *Echo) *Router

NewRouter returns a new Router instance.

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

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

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()`.

Reverse generates a URL from route name and provided parameters.

func (r Router) Routes() []Route

Routes returns the registered routes.

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, {{.}}!")), }

Render renders the template with given data.

type TrustOption func(*ipChecker)

TrustOption is config for which IP address to trust

TrustIPRange add trustable IP ranges using CIDR notation.

func TrustLinkLocal(v bool) TrustOption

TrustLinkLocal configures if you trust link-local address (default: true).

func TrustLoopback(v bool) TrustOption

TrustLoopback configures if you trust loopback address (default: true).

func TrustPrivateNet(v bool) TrustOption

TrustPrivateNet configures if you trust private network address (default: true).

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

Validator is the interface that wraps the Validate function.

ValueBinder provides utility methods for binding query or path parameter to various Go built-in types

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(c Context) *ValueBinder

PathParamsBinder creates path parameter value binder

func QueryParamsBinder(c Context) *ValueBinder

QueryParamsBinder creates query parameter value binder

BindError returns first seen bind error and resets/empties binder errors for further calls

// 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 (b *ValueBinder) BindErrors() []error

BindErrors returns all bind errors and resets/empties binder errors for further calls

// 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 (b *ValueBinder) BindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder

BindUnmarshaler binds parameter to destination implementing BindUnmarshaler interface

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

Bool binds parameter to bool variable

Bools binds parameter values to slice of bool variables

Byte binds parameter to byte variable

CustomFunc binds parameter values with Func. Func is called only when parameter values exist.

// 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

Duration binds parameter to time.Duration variable

Durations binds parameter values to slice of time.Duration variables

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

Float32 binds parameter to float32 variable

Float32s binds parameter values to slice of float32 variables

Float64 binds parameter to float64 variable

Float64s binds parameter values to slice of float64 variables

Int binds parameter to int variable

Int16 binds parameter to int16 variable

Int16s binds parameter to slice of int16

Int32 binds parameter to int32 variable

Int32s binds parameter to slice of int32

Int64 binds parameter to int64 variable

Int64s binds parameter to slice of int64

Int8 binds parameter to int8 variable

Int8s binds parameter to slice of int8

Ints binds parameter to slice of int

JSONUnmarshaler binds parameter to destination implementing json.Unmarshaler interface

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 (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

MustBool requires parameter value to exist to bind to bool variable. Returns error when value does not exist

MustBools requires parameter values to exist to bind to slice of bool variables. Returns error when values does not exist

MustByte requires parameter value to exist to bind to byte variable. Returns error when value does not exist

MustCustomFunc requires parameter values to exist to bind with Func. Returns error when value does not exist.

MustDuration requires parameter value to exist to bind to time.Duration variable. Returns error when value does not exist

MustDurations requires parameter values to exist to bind to slice of time.Duration variables. Returns error when values does not exist

MustFloat32 requires parameter value to exist to bind to float32 variable. Returns error when value does not exist

MustFloat32s requires parameter values to exist to bind to slice of float32 variables. Returns error when values does not exist

MustFloat64 requires parameter value to exist to bind to float64 variable. Returns error when value does not exist

MustFloat64s requires parameter values to exist to bind to slice of float64 variables. Returns error when values does not exist

MustInt requires parameter value to exist to bind to int variable. Returns error when value does not exist

MustInt16 requires parameter value to exist to bind to int16 variable. Returns error when value does not exist

MustInt16s requires parameter value to exist to bind to int16 slice variable. Returns error when value does not exist

MustInt32 requires parameter value to exist to bind to int32 variable. Returns error when value does not exist

MustInt32s requires parameter value to exist to bind to int32 slice variable. Returns error when value does not exist

MustInt64 requires parameter value to exist to bind to int64 variable. Returns error when value does not exist

MustInt64s requires parameter value to exist to bind to int64 slice variable. Returns error when value does not exist

MustInt8 requires parameter value to exist to bind to int8 variable. Returns error when value does not exist

MustInt8s requires parameter value to exist to bind to int8 slice variable. Returns error when value does not exist

MustInts requires parameter value to exist to bind to int slice variable. Returns error when value does not exist

MustJSONUnmarshaler requires parameter value to exist to bind to destination implementing json.Unmarshaler interface. Returns error when value does not exist

MustString requires parameter value to exist to bind to string variable. Returns error when value does not exist

MustStrings requires parameter values to exist to bind to slice of string variables. Returns error when value does not exist

MustTextUnmarshaler requires parameter value to exist to bind to destination implementing encoding.TextUnmarshaler interface. Returns error when value does not exist

MustTime requires parameter value to exist to bind to time.Time variable. Returns error when value does not exist

MustTimes requires parameter values to exist to bind to slice of time.Time variables. Returns error when values does not exist

MustUint requires parameter value to exist to bind to uint variable. Returns error when value does not exist

MustUint16 requires parameter value to exist to bind to uint16 variable. Returns error when value does not exist

MustUint16s requires parameter value to exist to bind to uint16 slice variable. Returns error when value does not exist

MustUint32 requires parameter value to exist to bind to uint32 variable. Returns error when value does not exist

MustUint32s requires parameter value to exist to bind to uint32 slice variable. Returns error when value does not exist

MustUint64 requires parameter value to exist to bind to uint64 variable. Returns error when value does not exist

MustUint64s requires parameter value to exist to bind to uint64 slice variable. Returns error when value does not exist

MustUint8 requires parameter value to exist to bind to uint8 variable. Returns error when value does not exist

MustUint8s requires parameter value to exist to bind to uint8 slice variable. Returns error when value does not exist

MustUints requires parameter value to exist to bind to uint slice variable. Returns error when value does not exist

MustUnixTime requires parameter value to exist to bind to time.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:

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:

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:

String binds parameter to string variable

Strings binds parameter values to slice of string

TextUnmarshaler binds parameter to destination implementing encoding.TextUnmarshaler interface

Time binds parameter to time.Time variable

Times binds parameter values to slice of time.Time variables

Uint binds parameter to uint variable

Uint16 binds parameter to uint16 variable

Uint16s binds parameter to slice of uint16

Uint32 binds parameter to uint32 variable

Uint32s binds parameter to slice of uint32

Uint64 binds parameter to uint64 variable

Uint64s binds parameter to slice of uint64

Uint8 binds parameter to uint8 variable

Uint8s binds parameter to slice of uint8

Uints binds parameter to slice of uint

UnixTime binds parameter to time.Time variable (in local Time corresponding to the given Unix time).

Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00

Note:

UnixTimeMilli binds parameter to time.Time variable (in local time corresponding to the given Unix time in millisecond precision).

Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00

Note:

UnixTimeNano binds parameter to time.Time variable (in local time corresponding to the given Unix time in nanosecond precision).

Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00

Note: