echo

package
v0.0.0-...-e7b3743 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2020 License: MIT, MIT Imports: 20 Imported by: 0

README

Echo GoDoc License Build Status Coverage Status

A fast and unfancy micro web framework for Go.

Features

  • Fast HTTP router which smartly prioritize routes.
  • Extensible middleware, supports:
    • echo.MiddlewareFunc
    • func(echo.HandlerFunc) echo.HandlerFunc
    • echo.HandlerFunc
    • func(*echo.Context) error
    • func(http.Handler) http.Handler
    • http.Handler
    • http.HandlerFunc
    • func(http.ResponseWriter, *http.Request)
  • Extensible handler, supports:
    • echo.HandlerFunc
    • func(*echo.Context) error
    • http.Handler
    • http.HandlerFunc
    • func(http.ResponseWriter, *http.Request)
  • Sub-router/Groups
  • Handy functions to send variety of HTTP response:
    • HTML
    • HTML via templates
    • String
    • JSON
    • JSONP
    • XML
    • File
    • NoContent
    • Redirect
    • Error
  • Build-in support for:
    • Favicon
    • Index file
    • Static files
    • WebSocket
  • Centralized HTTP error handling.
  • Customizable HTTP request binding function.
  • Customizable HTTP response rendering function, allowing you to use any HTML template engine.

Performance

Based on [vishr/go-http-routing-benchmark] (https://github.com/vishr/go-http-routing-benchmark), June 5, 2015.

Echo: 38662 ns/op, 0 B/op, 0 allocs/op

Performance

BenchmarkAce_GithubAll              20000             93675 ns/op           13792 B/op      167 allocs/op
BenchmarkBear_GithubAll             10000            264194 ns/op           79952 B/op      943 allocs/op
BenchmarkBeego_GithubAll             2000           1109160 ns/op          146272 B/op      2092 allocs/op
BenchmarkBone_GithubAll              1000           2063973 ns/op          648016 B/op     8119 allocs/op
BenchmarkDenco_GithubAll            20000             83114 ns/op           20224 B/op       167 allocs/op
BenchmarkEcho_GithubAll             30000             38662 ns/op               0 B/op        0 allocs/op
BenchmarkGin_GithubAll              30000             43467 ns/op               0 B/op        0 allocs/op
BenchmarkGocraftWeb_GithubAll        5000            386829 ns/op          133280 B/op      1889 allocs/op
BenchmarkGoji_GithubAll              3000            561131 ns/op           56113 B/op      334 allocs/op
BenchmarkGoJsonRest_GithubAll        3000            490789 ns/op          135995 B/op      2940 allocs/op
BenchmarkGoRestful_GithubAll          100          15569513 ns/op          797239 B/op      7725 allocs/op
BenchmarkGorillaMux_GithubAll         200           7431130 ns/op          153137 B/op      1791 allocs/op
BenchmarkHttpRouter_GithubAll       30000             51192 ns/op           13792 B/op       167 allocs/op
BenchmarkHttpTreeMux_GithubAll      10000            138164 ns/op           56112 B/op       334 allocs/op
BenchmarkKocha_GithubAll            10000            139625 ns/op           23304 B/op       843 allocs/op
BenchmarkMacaron_GithubAll           2000            709932 ns/op          224960 B/op      2315 allocs/op
BenchmarkMartini_GithubAll            100          10261331 ns/op          237953 B/op      2686 allocs/op
BenchmarkPat_GithubAll                500           3989686 ns/op         1504104 B/op    32222 allocs/op
BenchmarkPossum_GithubAll            5000            259165 ns/op           97441 B/op       812 allocs/op
BenchmarkR2router_GithubAll         10000            240345 ns/op           77328 B/op      1182 allocs/op
BenchmarkRevel_GithubAll             2000           1203336 ns/op          345554 B/op      5918 allocs/op
BenchmarkRivet_GithubAll            10000            247213 ns/op           84272 B/op      1079 allocs/op
BenchmarkTango_GithubAll             5000            379960 ns/op           87081 B/op      2470 allocs/op
BenchmarkTigerTonic_GithubAll        2000            931401 ns/op          241089 B/op      6052 allocs/op
BenchmarkTraffic_GithubAll            200           7292170 ns/op         2664770 B/op     22390 allocs/op
BenchmarkVulcan_GithubAll            5000            271682 ns/op           19894 B/op       609 allocs/op
BenchmarkZeus_GithubAll              2000            748827 ns/op          300688 B/op     2648 allocs/op

Echo System

Who's using Echo?
Community created packages around Echo

Want to get listed?

Installation

$ go get github.com/labstack/echo

Recipes

Guide

Contribute

Use issues for everything

  • Report problems
  • Discuss before sending a pull request
  • Suggest new features/recipes
  • Improve/fix documentation

Credits

Documentation

Overview

Package echo implements a fast and unfancy micro web framework for Go.

Example:

package main

import (
    "net/http"

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

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

func main() {
    e := echo.New()

    e.Use(mw.Logger())
    e.Use(mw.Recover())

    e.Get("/", hello)

    e.Run(":1323")
}

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

Index

Constants

View Source
const (
	// CONNECT HTTP method
	CONNECT = "CONNECT"
	// DELETE HTTP method
	DELETE = "DELETE"
	// GET HTTP method
	GET = "GET"
	// HEAD HTTP method
	HEAD = "HEAD"
	// OPTIONS HTTP method
	OPTIONS = "OPTIONS"
	// PATCH HTTP method
	PATCH = "PATCH"
	// POST HTTP method
	POST = "POST"
	// PUT HTTP method
	PUT = "PUT"
	// TRACE HTTP method
	TRACE = "TRACE"

	ApplicationJSON                  = "application/json"
	ApplicationJSONCharsetUTF8       = ApplicationJSON + "; " + CharsetUTF8
	ApplicationJavaScript            = "application/javascript"
	ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
	ApplicationXML                   = "application/xml"
	ApplicationXMLCharsetUTF8        = ApplicationXML + "; " + CharsetUTF8
	ApplicationForm                  = "application/x-www-form-urlencoded"
	ApplicationProtobuf              = "application/protobuf"
	ApplicationMsgpack               = "application/msgpack"
	TextHTML                         = "text/html"
	TextHTMLCharsetUTF8              = TextHTML + "; " + CharsetUTF8
	TextPlain                        = "text/plain"
	TextPlainCharsetUTF8             = TextPlain + "; " + CharsetUTF8
	MultipartForm                    = "multipart/form-data"

	CharsetUTF8 = "charset=utf-8"

	AcceptEncoding     = "Accept-Encoding"
	Authorization      = "Authorization"
	ContentDisposition = "Content-Disposition"
	ContentEncoding    = "Content-Encoding"
	ContentLength      = "Content-Length"
	ContentType        = "Content-Type"
	Location           = "Location"
	Upgrade            = "Upgrade"
	Vary               = "Vary"
	WWWAuthenticate    = "WWW-Authenticate"
	XForwardedFor      = "X-Forwarded-For"
	XRealIP            = "X-Real-IP"

	WebSocket = "websocket"
)

Variables

View Source
var (
	ErrUnsupportedMediaType  = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrRendererNotRegistered = errors.New("renderer not registered")
	ErrInvalidRedirectCode   = errors.New("invalid redirect status code")
)

Functions

This section is empty.

Types

type Binder

type Binder interface {
	Bind(*http.Request, interface{}) error
}

Binder is the interface that wraps the Bind method.

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

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

func NewContext

func NewContext(req *http.Request, res *Response, e *Echo) *Context

NewContext creates a Context object.

func (*Context) Bind

func (c *Context) Bind(i interface{}) error

Bind binds the request body into specified type `i`. The default binder does it based on Content-Type header.

func (*Context) Echo

func (c *Context) Echo() *Echo

Echo returns the `Echo` instance.

func (*Context) Error

func (c *Context) Error(err error)

Error invokes the registered HTTP error handler. Generally used by middleware.

func (*Context) File

func (c *Context) File(path, name string, attachment bool) (err error)

File sends a response with the content of the file. If `attachment` is set to true, the client is prompted to save the file with provided `name`, name can be empty, in that case name of the file is used.

func (*Context) Form

func (c *Context) Form(name string) string

Form returns form parameter by name.

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get retrieves data from the context.

func (*Context) HTML

func (c *Context) HTML(code int, html string) (err error)

HTML sends an HTTP response with status code.

func (*Context) JSON

func (c *Context) JSON(code int, i interface{}) (err error)

JSON sends a JSON response with status code.

func (*Context) JSONIndent

func (c *Context) JSONIndent(code int, i interface{}, prefix string, indent string) (err error)

JSONIndent sends a JSON response with status code, but it applies prefix and indent to format the output.

func (*Context) JSONP

func (c *Context) JSONP(code int, callback string, i interface{}) (err error)

JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.

func (*Context) NoContent

func (c *Context) NoContent(code int) error

NoContent sends a response with no body and a status code.

func (*Context) P

func (c *Context) P(i int) (value string)

P returns path parameter by index.

func (*Context) Param

func (c *Context) Param(name string) (value string)

Param returns path parameter by name.

func (*Context) Path

func (c *Context) Path() string

Path returns the registered path for the handler.

func (*Context) Query

func (c *Context) Query(name string) string

Query returns query parameter by name.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect redirects the request using http.Redirect with status code.

func (*Context) Render

func (c *Context) Render(code int, name string, data interface{}) (err error)

Render renders a template with data and sends a text/html response with status code. Templates can be registered using `Echo.SetRenderer()`.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns *http.Request.

func (*Context) Response

func (c *Context) Response() *Response

Response returns *Response.

func (*Context) Set

func (c *Context) Set(key string, val interface{})

Set saves data in the context.

func (*Context) Socket

func (c *Context) Socket() *websocket.Conn

Socket returns *websocket.Conn.

func (*Context) String

func (c *Context) String(code int, s string) (err error)

String sends a string response with status code.

func (*Context) XML

func (c *Context) XML(code int, i interface{}) (err error)

XML sends an XML response with status code.

func (*Context) XMLIndent

func (c *Context) XMLIndent(code int, i interface{}, prefix string, indent string) (err error)

XMLIndent sends an XML response with status code, but it applies prefix and indent to format the output.

type Echo

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

Echo is the top-level framework instance.

func New

func New() (e *Echo)

New creates an instance of Echo.

func (*Echo) Any

func (e *Echo) Any(path string, h Handler)

Any adds a route > handler to the router for all HTTP methods.

func (*Echo) AutoIndex

func (e *Echo) AutoIndex(on bool)

AutoIndex enable/disable automatically creating an index page for the directory.

func (*Echo) Connect

func (e *Echo) Connect(path string, h Handler)

Connect adds a CONNECT route > handler to the router.

func (*Echo) Debug

func (e *Echo) Debug() bool

Debug returns debug mode (enabled or disabled).

func (*Echo) DefaultHTTPErrorHandler

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

DefaultHTTPErrorHandler invokes the default HTTP error handler.

func (*Echo) Delete

func (e *Echo) Delete(path string, h Handler)

Delete adds a DELETE route > handler to the router.

func (*Echo) Favicon

func (e *Echo) Favicon(file string)

Favicon serves the default favicon - GET /favicon.ico.

func (*Echo) Get

func (e *Echo) Get(path string, h Handler)

Get adds a GET route > handler to the router.

func (*Echo) Group

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

Group creates a new sub router with prefix. It inherits all properties from the parent. Passing middleware overrides parent middleware.

func (*Echo) HTTP2

func (e *Echo) HTTP2(on bool)

HTTP2 enable/disable HTTP2 support.

func (*Echo) Head

func (e *Echo) Head(path string, h Handler)

Head adds a HEAD route > handler to the router.

func (*Echo) Hook

func (e *Echo) Hook(h http.HandlerFunc)

Hook registers a callback which is invoked from `Echo#ServerHTTP` as the first statement. Hook is useful if you want to modify response/response objects even before it hits the router or any middleware.

func (*Echo) Index

func (e *Echo) Index(file string)

Index serves index file.

func (*Echo) Logger

func (e *Echo) Logger() Logger

Logger returns the logger instance.

func (*Echo) Match

func (e *Echo) Match(methods []string, path string, h Handler)

Match adds a route > handler to the router for multiple HTTP methods provided.

func (*Echo) Options

func (e *Echo) Options(path string, h Handler)

Options adds an OPTIONS route > handler to the router.

func (*Echo) Patch

func (e *Echo) Patch(path string, h Handler)

Patch adds a PATCH route > handler to the router.

func (*Echo) Post

func (e *Echo) Post(path string, h Handler)

Post adds a POST route > handler to the router.

func (*Echo) Put

func (e *Echo) Put(path string, h Handler)

Put adds a PUT route > handler to the router.

func (*Echo) Router

func (e *Echo) Router() *Router

Router returns router.

func (*Echo) Routes

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

Routes returns the registered routes.

func (*Echo) Run

func (e *Echo) Run(addr string)

Run runs a server.

func (*Echo) RunServer

func (e *Echo) RunServer(s *http.Server)

RunServer runs a custom server.

func (*Echo) RunTLS

func (e *Echo) RunTLS(addr, crtFile, keyFile string)

RunTLS runs a server with TLS configuration.

func (*Echo) RunTLSServer

func (e *Echo) RunTLSServer(s *http.Server, crtFile, keyFile string)

RunTLSServer runs a custom server with TLS configuration.

func (*Echo) ServeDir

func (e *Echo) ServeDir(path, dir string)

ServeDir serves files from a directory.

func (*Echo) ServeFile

func (e *Echo) ServeFile(path, file string)

ServeFile serves a file.

func (*Echo) ServeHTTP

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

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

func (*Echo) Server

func (e *Echo) Server(addr string) *http.Server

Server returns the internal *http.Server.

func (*Echo) SetBinder

func (e *Echo) SetBinder(b Binder)

SetBinder registers a custom binder. It's invoked by Context.Bind().

func (*Echo) SetDebug

func (e *Echo) SetDebug(on bool)

SetDebug enable/disable debug mode.

func (*Echo) SetHTTPErrorHandler

func (e *Echo) SetHTTPErrorHandler(h HTTPErrorHandler)

SetHTTPErrorHandler registers a custom Echo.HTTPErrorHandler.

func (*Echo) SetLogger

func (e *Echo) SetLogger(logger Logger)

SetLogger sets the logger instance.

func (*Echo) SetRenderer

func (e *Echo) SetRenderer(r Renderer)

SetRenderer registers an HTML template renderer. It's invoked by Context.Render().

func (*Echo) Static

func (e *Echo) Static(path, dir string)

Static serves static files from a directory. It's an alias for `Echo.ServeDir`

func (*Echo) Trace

func (e *Echo) Trace(path string, h Handler)

Trace adds a TRACE route > handler to the router.

func (*Echo) URI

func (e *Echo) URI(h Handler, params ...interface{}) string

URI generates a URI from handler.

func (*Echo) URL

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

URL is an alias for `URI` function.

func (*Echo) Use

func (e *Echo) Use(m ...Middleware)

Use adds handler to the middleware chain.

func (*Echo) WebSocket

func (e *Echo) WebSocket(path string, h HandlerFunc)

WebSocket adds a WebSocket route > handler to the router.

type Group

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

Group is a set of subroutes 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

func (g *Group) Any(path string, h Handler)

Any implements the echo.Any interface for subroutes within the Group.

func (*Group) Connect

func (g *Group) Connect(path string, h Handler)

Connect implements the echo.Connect interface for subroutes within the Group.

func (*Group) Delete

func (g *Group) Delete(path string, h Handler)

Delete implements the echo.Delete interface for subroutes within the Group.

func (*Group) Get

func (g *Group) Get(path string, h Handler)

Get implements the echo.Get interface for subroutes within the Group.

func (*Group) Group

func (g *Group) Group(prefix string, m ...Middleware) *Group

Group implements the echo.Group interface for subroutes within the Group.

func (*Group) Head

func (g *Group) Head(path string, h Handler)

Head implements the echo.Head interface for subroutes within the Group.

func (*Group) Match

func (g *Group) Match(methods []string, path string, h Handler)

Match implements the echo.Match interface for subroutes within the Group.

func (*Group) Options

func (g *Group) Options(path string, h Handler)

Options implements the echo.Options interface for subroutes within the Group.

func (*Group) Patch

func (g *Group) Patch(path string, h Handler)

Patch implements the echo.Patch interface for subroutes within the Group.

func (*Group) Post

func (g *Group) Post(path string, h Handler)

Post implements the echo.Post interface for subroutes within the Group.

func (*Group) Put

func (g *Group) Put(path string, h Handler)

Put implements the echo.Put interface for subroutes within the Group.

func (*Group) ServeDir

func (g *Group) ServeDir(path, root string)

ServeDir implements the echo.ServeDir interface for subroutes within the Group.

func (*Group) ServeFile

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

ServeFile implements the echo.ServeFile interface for subroutes within the Group.

func (*Group) Static

func (g *Group) Static(path, root string)

Static implements the echo.Static interface for subroutes within the Group.

func (*Group) Trace

func (g *Group) Trace(path string, h Handler)

Trace implements the echo.Trace interface for subroutes within the Group.

func (*Group) Use

func (g *Group) Use(m ...Middleware)

Use implements the echo.Use interface for subroutes within the Group.

func (*Group) WebSocket

func (g *Group) WebSocket(path string, h HandlerFunc)

WebSocket implements the echo.WebSocket interface for subroutes within the Group.

type HTTPError

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

HTTPError represents an error that occured while handling a request.

func NewHTTPError

func NewHTTPError(code int, msg ...string) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Code

func (e *HTTPError) Code() int

Code returns code.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns message.

func (*HTTPError) SetCode

func (e *HTTPError) SetCode(code int)

SetCode sets code.

type HTTPErrorHandler

type HTTPErrorHandler func(error, *Context)

HTTPErrorHandler is a centralized HTTP error handler.

type Handler

type Handler interface{}

Handler ...

type HandlerFunc

type HandlerFunc func(*Context) error

HandlerFunc ...

type Logger

type Logger interface {
	Debug(...interface{})
	Debugf(string, ...interface{})

	Info(...interface{})
	Infof(string, ...interface{})

	Warn(...interface{})
	Warnf(string, ...interface{})

	Error(...interface{})
	Errorf(string, ...interface{})

	Fatal(...interface{})
	Fatalf(string, ...interface{})
}

Logger is the interface that declares echo's logging system.

type Middleware

type Middleware interface{}

Middleware ...

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc ...

type Renderer

type Renderer interface {
	Render(w io.Writer, name string, data interface{}) error
}

Renderer is the interface that wraps the Render method.

type Response

type Response struct {
	// 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 http.ResponseWriter(https://golang.org/pkg/net/http/#ResponseWriter)

func NewResponse

func NewResponse(w http.ResponseWriter, e *Echo) *Response

NewResponse creates a new instance of Response.

func (*Response) CloseNotify

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)

func (*Response) Committed

func (r *Response) Committed() bool

Committed asserts whether or not the response has been committed to.

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 [ResponseWriter.Trailers](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) SetWriter

func (r *Response) SetWriter(w http.ResponseWriter)

SetWriter sets the http.ResponseWriter instance for this Response.

func (*Response) Size

func (r *Response) Size() int64

Size returns the current size, in bytes, of the response.

func (*Response) Status

func (r *Response) Status() int

Status returns the HTTP status code of the response.

func (*Response) Write

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

Write wraps and implements the http.Response.Write specification. Additionally, Write will increment the size of the current response. See http.Response.Write(https://golang.org/pkg/net/http/#Response.Write)

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.

func (*Response) Writer

func (r *Response) Writer() http.ResponseWriter

Writer returns the http.ResponseWriter instance for this Response.

type Route

type Route struct {
	Method  string
	Path    string
	Handler Handler
}

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

Router implements the http.Handler specification and can be registered to serve requests.

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

Add registers a new route with a matcher for the URL path.

func (*Router) Find

func (r *Router) Find(method, path string, ctx *Context) (h HandlerFunc, e *Echo)

Find dispatches the request to the handler whos route is matched with the specified request path.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the Handler interface and can be registered to serve a particular path or subtree in an HTTP server. See Router.Find()

type Validator

type Validator interface {
	Validate() error
}

Validator is the interface that wraps the Validate method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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