echo

package module
v2.0.0-beta.2+incompat... Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2016 License: MIT Imports: 21 Imported by: 0

README

NOTICE

Echo GoDoc License Build Status Coverage Status

A fast and unfancy micro web framework for Go.

Features

  • Fast HTTP router which smartly prioritize routes.
  • Run with standard HTTP server or FastHTTP server.
  • Extensible middleware framework.
  • Router groups with nesting.
  • Handy functions to send variety of HTTP responses.
  • Centralized HTTP error handling.
  • Template rendering with any template engine.

Performance

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

Performance

Getting Started

Installation
$ go get github.com/labstack/echo
Hello, World!

Create main.go

package main

import (
	"net/http"

	"github.com/labstack/echo"
	"github.com/labstack/echo/engine/standard"
	"github.com/labstack/echo/middleware"
)

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

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

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

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

	// Start server
	e.Run(standard.New(":1323"))
}

Start server

$ go run main.go

Browse to http://localhost:1323 and you should see Hello, World! on the page.

Next?

Contribute

Use issues for everything

  • Report issues
  • Discuss before sending pull request
  • Suggest new features
  • Improve/fix documentation

Credits

License

MIT

Documentation

Overview

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

Example:

package main

import (
    "net/http"

    "github.com/labstack/echo"
    "github.com/labstack/echo/engine/standard"
    "github.com/labstack/echo/middleware"
)

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

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

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

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

    // Start server
    e.Run(standard.New(":1323"))
}

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

Index

Constants

View Source
const (
	CONNECT = "CONNECT"
	DELETE  = "DELETE"
	GET     = "GET"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	POST    = "POST"
	PUT     = "PUT"
	TRACE   = "TRACE"
)

HTTP methods

View Source
const (
	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"
	OctetStream                      = "application/octet-stream"
)

Media types

View Source
const (
	AcceptEncoding     = "Accept-Encoding"
	Authorization      = "Authorization"
	ContentDisposition = "Content-Disposition"
	ContentEncoding    = "Content-Encoding"
	ContentLength      = "Content-Length"
	ContentType        = "Content-Type"
	LastModified       = "Last-Modified"
	Location           = "Location"
	Upgrade            = "Upgrade"
	Vary               = "Vary"
	WWWAuthenticate    = "WWW-Authenticate"
	XForwardedFor      = "X-Forwarded-For"
	XRealIP            = "X-Real-IP"
)

Headers

View Source
const (
	CharsetUTF8 = "charset=utf-8"
)

Charset

Variables

View Source
var (
	ErrUnsupportedMediaType  = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound              = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized          = NewHTTPError(http.StatusUnauthorized)
	ErrMethodNotAllowed      = NewHTTPError(http.StatusMethodNotAllowed)
	ErrRendererNotRegistered = errors.New("renderer not registered")
	ErrInvalidRedirectCode   = errors.New("invalid redirect status code")
)

Errors

Functions

func ServeContent

func ServeContent(req engine.Request, res engine.Response, f http.File, fi os.FileInfo) error

ServeContent sends a response from `io.Reader`. It automatically sets the `Content-Type` and `Last-Modified` headers.

Types

type Binder added in v1.2.0

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

Binder is the interface that wraps the Bind function.

type Context

type Context interface {
	netContext.Context

	// NetContext returns `http://blog.golang.org/context.Context` interface.
	NetContext() netContext.Context

	// SetNetContext sets `http://blog.golang.org/context.Context` interface.
	SetNetContext(netContext.Context)

	// Request returns `engine.Request` interface.
	Request() engine.Request

	// Request returns `engine.Response` interface.
	Response() engine.Response

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

	// P returns path parameter by index.
	P(int) string

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

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

	// QueryParam returns the query param for the provided name. It is an alias
	// for `engine.URL#QueryParam()`.
	QueryParam(string) string

	// FormValue returns the form field value for the provided name. It is an
	// alias for `engine.Request#FormValue()`.
	FormValue(string) string

	// FormFile returns the multipart form file for the provided name. It is an
	// alias for `engine.Request#FormFile()`.
	FormFile(string) (*multipart.FileHeader, error)

	// MultipartForm returns the multipart form. It is an alias for `engine.Request#MultipartForm()`.
	MultipartForm() (*multipart.Form, error)

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

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

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

	// Attachment sends a response from `io.Reader` as attachment, prompting client
	// to save the file.
	Attachment(io.Reader, 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 implements `Handler` interface.
	Handle(Context) error

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

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

	// Object returns the `context` instance.
	Object() *context

	// Reset resets the context after request completes. It must be called along
	// with `Echo#GetContext()` and `Echo#PutContext()`. See `Echo#ServeHTTP()`
	Reset(engine.Request, engine.Response)
}

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

func NewContext added in v0.0.13

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

NewContext creates a Context object.

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

func (e *Echo) Any(path string, handler Handler, middleware ...Middleware)

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 Handler, m ...Middleware)

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

func (*Echo) Debug added in v0.0.13

func (e *Echo) Debug() bool

Debug returns debug mode (enabled or disabled).

func (*Echo) DefaultHTTPErrorHandler added in v1.0.0

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, m ...Middleware)

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

func (*Echo) File

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

File serves provided file for `/<path>` HTTP path.

func (*Echo) Get

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

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

func (*Echo) GetContext

func (e *Echo) GetContext() Context

GetContext returns `Context` from the sync.Pool. You must return the context by calling `PutContext()`.

func (*Echo) Group added in v0.0.4

func (e *Echo) Group(prefix string, m ...Middleware) (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 Handler, m ...Middleware)

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

func (*Echo) Logger added in v1.4.1

func (e *Echo) Logger() *log.Logger

Logger returns the logger instance.

func (*Echo) Match added in v1.2.0

func (e *Echo) Match(methods []string, path string, handler Handler, middleware ...Middleware)

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

func (*Echo) Options

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

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 Handler, m ...Middleware)

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 Handler, m ...Middleware)

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

func (*Echo) Pre

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

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

func (*Echo) Put

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

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

func (*Echo) PutContext

func (e *Echo) PutContext(c Context)

PutContext returns `Context` instance back to the sync.Pool. You must call it after `GetContext()`.

func (*Echo) Router

func (e *Echo) Router() *Router

Router returns router.

func (*Echo) Routes added in v1.0.0

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

Routes returns the registered routes.

func (*Echo) Run

func (e *Echo) Run(s engine.Server)

Run starts the HTTP server.

func (*Echo) ServeHTTP

func (e *Echo) ServeHTTP(req engine.Request, res engine.Response)

func (*Echo) SetBinder added in v0.0.14

func (e *Echo) SetBinder(b Binder)

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

func (*Echo) SetDebug added in v0.0.14

func (e *Echo) SetDebug(on bool)

SetDebug enable/disable debug mode.

func (*Echo) SetHTTPErrorHandler added in v0.0.14

func (e *Echo) SetHTTPErrorHandler(h HTTPErrorHandler)

SetHTTPErrorHandler registers a custom Echo.HTTPErrorHandler.

func (*Echo) SetLogLevel added in v1.4.1

func (e *Echo) SetLogLevel(l uint8)

SetLogLevel sets the log level for the logger. Default value is `log.ERROR`.

func (*Echo) SetLogOutput added in v1.4.1

func (e *Echo) SetLogOutput(w io.Writer)

SetLogOutput sets the output destination for the logger. Default value is `os.Std*`

func (*Echo) SetLogPrefix added in v1.4.1

func (e *Echo) SetLogPrefix(prefix string)

SetLogPrefix sets the prefix for the logger. Default value is `echo`.

func (*Echo) SetRenderer added in v0.0.14

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(prefix, root string)

Static serves files from provided `root` directory for `/<prefix>*` HTTP path.

func (*Echo) Trace

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

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 Handler, params ...interface{}) string

URI generates a URI from handler.

func (*Echo) URL added in v0.0.11

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

URL is an alias for `URI` function.

func (*Echo) Use

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

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 Handler, middleware ...Middleware)

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

func (*Group) Connect added in v0.0.16

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

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

func (*Group) Delete added in v0.0.16

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

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

func (*Group) Get added in v0.0.16

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

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

func (*Group) Group added in v0.0.16

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

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

func (*Group) Head added in v0.0.16

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

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 Handler, middleware ...Middleware)

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

func (*Group) Options added in v0.0.16

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

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

func (*Group) Patch added in v0.0.16

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

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

func (*Group) Post added in v0.0.16

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

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

func (*Group) Put added in v0.0.16

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

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

func (*Group) Trace added in v0.0.16

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

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

func (*Group) Use added in v0.0.16

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

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

type HTTPError added in v0.0.12

type HTTPError struct {
	Code    int
	Message string
}

HTTPError represents an error that occured while handling a request.

func NewHTTPError added in v0.0.14

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

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Error added in v0.0.12

func (e *HTTPError) Error() string

Error makes it compatible with `error` interface.

type HTTPErrorHandler added in v0.0.10

type HTTPErrorHandler func(error, Context)

HTTPErrorHandler is a centralized HTTP error handler.

type Handler

type Handler interface {
	Handle(Context) error
}

Handler defines an interface to server HTTP requests via `Handle(Context)` function.

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc is an adapter to allow the use of `func(Context)` as an HTTP handler.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(c Context) error

Handle serves HTTP request.

type Middleware

type Middleware interface {
	Handle(Handler) Handler
}

Middleware defines an interface for middleware via `Handle(Handler) Handler` function.

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

MiddlewareFunc is an adapter to allow the use of `func(Handler) Handler` as middleware.

func WrapMiddleware

func WrapMiddleware(h Handler) MiddlewareFunc

WrapMiddleware wrap `echo.Handler` into `echo.MiddlewareFunc`.

func (MiddlewareFunc) Handle

func (f MiddlewareFunc) Handle(h Handler) Handler

Handle chains middleware.

type Renderer added in v0.0.7

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

Renderer is the interface that wraps the Render function.

type Route added in v1.0.0

type Route struct {
	Method  string
	Path    string
	Handler string
}

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 NewRouter

func NewRouter(e *Echo) *Router

NewRouter returns a new Router instance.

func (*Router) Add added in v0.0.16

func (r *Router) Add(method, path string, h Handler, e *Echo)

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

func (*Router) Find added in v0.0.16

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

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

For performance:

- Get context from `Echo#GetContext()` - Reset it `Context#Reset()` - Return it `Echo#PutContext()`.

func (*Router) Handle

func (r *Router) Handle(next Handler) Handler

Handle implements `echo.Middleware` which makes router a middleware.

func (*Router) Priority

func (r *Router) Priority() int

Priority is super secret.

type Validator added in v1.2.0

type Validator interface {
	Validate() error
}

Validator is the interface that wraps the Validate function.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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