HeaderAuthorization = "Authorization" · pkg.go.dev

Package echo implements high performance, minimalist Go web framework.

Example:

package main
import (
  "net/http"
  "github.com/labstack/echo"
  "github.com/labstack/echo/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 + "; " + 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 (
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"

	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
)

Headers

Errors

Error handlers

This section is empty.

type BindUnmarshaler interface {

	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method.

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

Binder is the interface that wraps the Bind method.

type Context interface {

	Request() *http.Request

	SetRequest(r *http.Request)

	Response() *Response

	IsTLS() bool

	IsWebSocket() bool

	Scheme() string


	RealIP() string

	Path() string

	SetPath(p string)

	Param(name string) string

	ParamNames() []string

	SetParamNames(names ...string)

	ParamValues() []string

	SetParamValues(values ...string)

	QueryParam(name string) string

	QueryParams() url.Values

	QueryString() string

	FormValue(name string) string

	FormParams() (url.Values, error)

	FormFile(name string) (*multipart.FileHeader, error)

	MultipartForm() (*multipart.Form, error)

	Cookie(name string) (*http.Cookie, error)

	SetCookie(cookie *http.Cookie)

	Cookies() []*http.Cookie

	Get(key string) interface{}

	Set(key string, val interface{})


	Bind(i interface{}) error


	Validate(i interface{}) error


	Render(code int, name string, data interface{}) error

	HTML(code int, html string) error

	HTMLBlob(code int, b []byte) error

	String(code int, s string) error

	JSON(code int, i interface{}) error

	JSONPretty(code int, i interface{}, indent string) error

	JSONBlob(code int, b []byte) error


	JSONP(code int, callback string, i interface{}) error


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

	XML(code int, i interface{}) error

	XMLPretty(code int, i interface{}, indent string) error

	XMLBlob(code int, b []byte) error

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

	Stream(code int, contentType string, r io.Reader) error

	File(file string) error


	Attachment(file string, name string) error

	Inline(file string, name string) error

	NoContent(code int) error

	Redirect(code int, url string) error

	Error(err error)

	Handler() HandlerFunc

	SetHandler(h HandlerFunc)

	Logger() Logger

	Echo() *Echo


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

Echo is the top-level framework instance.

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 and path with matching handler in the router with optional route-level middleware.

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 added in v1.0.0

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

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

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.

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.

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 an URL from route name and provided parameters.

func (e *Echo) Router() *Router

Router returns router.

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

Routes returns the registered 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.

StartServer starts a custom http server.

StartTLS starts an HTTPS server.

func (e *Echo) Static(prefix, root string) *Route

Static registers a new route with path prefix to serve static files from the provided root directory.

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

type Group struct {
}

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.

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

func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *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) Static(prefix, root string)

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

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 {
	Code     int
	Message  interface{}
	Internal error
}

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

type HTTPErrorHandler added in v0.0.10

type HTTPErrorHandler func(error, Context)

HTTPErrorHandler is a centralized HTTP error handler.

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc defines a function to serve HTTP requests.

func WrapHandler

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

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

func (r *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

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

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.

type Router struct {
}

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

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

Validator is the interface that wraps the Validate function.

Read the original on pkg.go.dev ↗