Documentation ¶
Overview ¶
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
Index ¶
- Constants
- Variables
- type Binder
- type Context
- type Echo
- func (e *Echo) AcquireContext() Context
- func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) DefaultHTTPErrorHandler(err error, c Context)
- func (e *Echo) File(path, file string)
- func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group)
- func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) Match(methods []string, path string, handler HandlerFunc, ...)
- func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context
- func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) Pre(middleware ...MiddlewareFunc)
- func (e *Echo) ReleaseContext(c Context)
- func (e *Echo) Router() *Router
- func (e *Echo) Routes() []Route
- func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (e *Echo) Shutdown(timeout time.Duration)
- func (e *Echo) ShutdownTLS(timeout time.Duration)
- func (e *Echo) Start(address string) error
- func (e *Echo) StartAutoTLS(address string) error
- func (e *Echo) StartServer(s *http.Server) error
- func (e *Echo) StartTLS(address string, certFile, keyFile string) (err error)
- func (e *Echo) Static(prefix, root string)
- func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string
- func (e *Echo) URL(h HandlerFunc, params ...interface{}) string
- func (e *Echo) Use(middleware ...MiddlewareFunc)
- type Group
- func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) File(path, file string)
- func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group
- func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Match(methods []string, path string, handler HandlerFunc, ...)
- func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Static(prefix, root string)
- func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Use(middleware ...MiddlewareFunc)
- type HTTPError
- type HTTPErrorHandler
- type HandlerFunc
- type Logger
- type Map
- type MiddlewareFunc
- type Renderer
- type Response
- func (r *Response) CloseNotify() <-chan bool
- func (r *Response) Flush()
- func (r *Response) Header() http.Header
- func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) SetWriter(w http.ResponseWriter)
- func (r *Response) Write(b []byte) (n int, err error)
- func (r *Response) WriteHeader(code int)
- func (r *Response) Writer() http.ResponseWriter
- type Route
- type Router
- type Validator
Constants ¶
const ( CONNECT = "CONNECT" DELETE = "DELETE" GET = "GET" HEAD = "HEAD" OPTIONS = "OPTIONS" PATCH = "PATCH" POST = "POST" PUT = "PUT" TRACE = "TRACE" )
HTTP methods
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types
const ( HeaderAcceptEncoding = "Accept-Encoding" 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" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXForwardedFor = "X-Forwarded-For" HeaderXRealIP = "X-Real-IP" HeaderServer = "Server" HeaderOrigin = "Origin" 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" HeaderXCSRFToken = "X-CSRF-Token" )
Headers
Variables ¶
var ( ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType) ErrNotFound = NewHTTPError(http.StatusNotFound) ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") )
Errors
var ( NotFoundHandler = func(c Context) error { return ErrNotFound } MethodNotAllowedHandler = func(c Context) error { return ErrMethodNotAllowed } )
Error handlers
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context interface { // Request returns `*http.Request`. Request() *http.Request // SetRequest sets `*http.Request`. SetRequest(*http.Request) // Request returns `*Response`. Response() *Response // IsTLS returns true if HTTP connection is TLS otherwise false. IsTLS() 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. RealIP() string // Path returns the registered path for the handler. Path() string // SetPath sets the registered path for the handler. SetPath(string) // Param returns path parameter by name. Param(string) string // ParamNames returns path parameter names. ParamNames() []string // SetParamNames sets path parameter names. SetParamNames(...string) // ParamValues returns path parameter values. ParamValues() []string // SetParamValues sets path parameter values. SetParamValues(...string) // QueryParam returns the query param for the provided name. QueryParam(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(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(string) (*multipart.FileHeader, error) // MultipartForm returns the multipart form. MultipartForm() (*multipart.Form, error) // Cookie returns the named cookie provided in the request. Cookie(string) (*http.Cookie, error) // SetCookie adds a `Set-Cookie` header in HTTP response. SetCookie(*http.Cookie) // Cookies returns the HTTP cookies sent with the request. Cookies() []*http.Cookie // Get retrieves data from the context. Get(string) interface{} // Set saves data in the context. Set(string, interface{}) // Bind binds the request body into provided type `i`. The default binder // does it based on Content-Type header. Bind(interface{}) error // Render renders a template with data and sends a text/html response with status // code. Templates can be registered using `Echo.Renderer`. Render(int, string, interface{}) error // HTML sends an HTTP response with status code. HTML(int, string) error // String sends a string response with status code. String(int, string) error // JSON sends a JSON response with status code. JSON(int, interface{}) error // JSONBlob sends a JSON blob response with status code. JSONBlob(int, []byte) error // JSONP sends a JSONP response with status code. It uses `callback` to construct // the JSONP payload. JSONP(int, string, interface{}) error // JSONPBlob sends a JSONP blob response with status code. It uses `callback` // to construct the JSONP payload. JSONPBlob(int, string, []byte) error // XML sends an XML response with status code. XML(int, interface{}) error // XMLBlob sends a XML blob response with status code. XMLBlob(int, []byte) error // Blob sends a blob response with status code and content type. Blob(int, string, []byte) error // Stream sends a streaming response with status code and content type. Stream(int, string, io.Reader) error // File sends a response with the content of the file. File(string) error // Attachment sends a response as attachment, prompting client to save the // file. Attachment(string, string) error // Inline sends a response as inline, opening the file in the browser. Inline(string, string) error // NoContent sends a response with no body and a status code. NoContent(int) error // Redirect redirects the request with status code. Redirect(int, string) error // Error invokes the registered HTTP error handler. Generally used by middleware. Error(err error) // Handler returns the matched handler by router. Handler() HandlerFunc // SetHandler sets the matched handler by router. SetHandler(HandlerFunc) // Logger returns the `Logger` instance. Logger() 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(*http.Request, 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 Echo ¶
type Echo struct { DisableHTTP2 bool Debug bool HTTPErrorHandler Binder Binder Renderer Renderer AutoTLSManager autocert.Manager ShutdownTimeout time.Duration Color *color.Color Logger Logger // contains filtered or unexported fields }
Echo is the top-level framework instance.
func (*Echo) AcquireContext ¶
AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.
func (*Echo) Any ¶ added in v1.2.0
func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Echo) CONNECT ¶
func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc)
CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) DELETE ¶
func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc)
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
DefaultHTTPErrorHandler invokes the default HTTP error handler.
func (*Echo) GET ¶
func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc)
GET registers a new GET route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) Group ¶ added in v0.0.4
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)
HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) Match ¶ added in v1.2.0
func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
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 ¶
NewContext returns a Context instance.
func (*Echo) OPTIONS ¶
func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc)
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)
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)
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)
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 ¶
ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.
func (*Echo) ServeHTTP ¶
func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (*Echo) ShutdownTLS ¶
ShutdownTLS gracefully shutdown the TLS server with timeout.
func (*Echo) StartAutoTLS ¶
StartAutoTLS starts the HTTPS server using certificates automatically from https://letsencrypt.org.
func (*Echo) StartServer ¶
StartServer runs a custom HTTP server.
func (*Echo) Static ¶
Static registers a new route with path prefix to serve static files from the provided root directory.
func (*Echo) TRACE ¶
func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc)
TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) URI ¶ added in v0.0.11
func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string
URI generates a URI from handler.
func (*Echo) URL ¶ added in v0.0.11
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 ¶ added in v0.0.16
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 middlware or functionality that should be separate from the parent echo instance while still inheriting from it.
func (*Group) Any ¶ added in v1.4.1
func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Any implements `Echo#Any()` for sub-routes within the Group.
func (*Group) CONNECT ¶
func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc)
CONNECT implements `Echo#CONNECT()` for sub-routes within the Group.
func (*Group) DELETE ¶
func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc)
DELETE implements `Echo#DELETE()` for sub-routes within the Group.
func (*Group) GET ¶
func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc)
GET implements `Echo#GET()` for sub-routes within the Group.
func (*Group) Group ¶ added in v0.0.16
func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *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)
HEAD implements `Echo#HEAD()` for sub-routes within the Group.
func (*Group) Match ¶ added in v1.4.1
func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Match implements `Echo#Match()` for sub-routes within the Group.
func (*Group) OPTIONS ¶
func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc)
OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group.
func (*Group) PATCH ¶
func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc)
PATCH implements `Echo#PATCH()` for sub-routes within the Group.
func (*Group) POST ¶
func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc)
POST implements `Echo#POST()` for sub-routes within the Group.
func (*Group) PUT ¶
func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc)
PUT implements `Echo#PUT()` for sub-routes within the Group.
func (*Group) Static ¶ added in v1.0.0
Static implements `Echo#Static()` for sub-routes within the Group.
func (*Group) TRACE ¶
func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc)
TRACE implements `Echo#TRACE()` for sub-routes within the Group.
func (*Group) Use ¶ added in v0.0.16
func (g *Group) Use(middleware ...MiddlewareFunc)
Use implements `Echo#Use()` for sub-routes within the Group.
type HTTPError ¶ added in v0.0.12
HTTPError represents an error that occurred while handling a request.
func NewHTTPError ¶ added in v0.0.14
NewHTTPError creates a new HTTPError instance.
type HTTPErrorHandler ¶ added in v0.0.10
HTTPErrorHandler is a centralized HTTP error handler.
type HandlerFunc ¶
HandlerFunc defines a function to server HTTP requests.
func WrapHandler ¶
func WrapHandler(h http.Handler) HandlerFunc
WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
type Logger ¶ added in v0.0.10
type Logger interface { Output() io.Writer SetOutput(io.Writer) Level() log.Lvl SetLevel(log.Lvl) Prefix() string SetPrefix(string) Print(...interface{}) Printf(string, ...interface{}) Printj(log.JSON) Debug(...interface{}) Debugf(string, ...interface{}) Debugj(log.JSON) Info(...interface{}) Infof(string, ...interface{}) Infoj(log.JSON) Warn(...interface{}) Warnf(string, ...interface{}) Warnj(log.JSON) Error(...interface{}) Errorf(string, ...interface{}) Errorj(log.JSON) Fatal(...interface{}) Fatalj(log.JSON) Fatalf(string, ...interface{}) Panic(...interface{}) Panicj(log.JSON) Panicf(string, ...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(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 Response ¶ added in v0.0.13
type Response struct { 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 ¶ added in v0.0.14
func NewResponse(w http.ResponseWriter, e *Echo) (r *Response)
NewResponse creates a new instance of Response.
func (*Response) CloseNotify ¶ added in v0.0.13
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)
func (*Response) Flush ¶ added in v0.0.13
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 ¶ added in v0.0.13
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 ¶ added in v0.0.13
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) SetWriter ¶ added in v0.0.15
func (r *Response) SetWriter(w http.ResponseWriter)
SetWriter sets the http.ResponseWriter instance for this Response.
func (*Response) Write ¶ added in v0.0.13
Write writes the data to the connection as part of an HTTP reply.
func (*Response) WriteHeader ¶ added in v0.0.13
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.
func (*Response) Writer ¶ added in v0.0.13
func (r *Response) Writer() http.ResponseWriter
Writer returns the http.ResponseWriter instance for this Response.
type Route ¶ added in v1.0.0
Route contains a handler and information for matching against requests.
type Router ¶ added in v0.0.16
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 (*Router) Add ¶ added in v0.0.16
func (r *Router) Add(method, path string, h HandlerFunc)
Add registers a new route for method and path with matching handler.