echo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2016 License: Apache-2.0 Imports: 25 Imported by: 949

README

Echo

Build Status Go Report Card

Echo is a fast and unfancy web framework for Go (Golang). Up to 10x faster than the rest.

Features

  • Optimized HTTP router which smartly prioritize routes.
  • Build robust and scalable RESTful APIs.
  • Run with standard HTTP server or FastHTTP server.
  • Group APIs.
  • Extensible middleware framework.
  • Define middleware at root, group or route level.
  • Handy functions to send variety of HTTP responses.
  • Centralized HTTP error handling.
  • Template rendering with any template engine.
  • Define your format for the logger.
  • Highly customizable.

Quick Start

Installation
$ go get github.com/webx-top/echo
Hello, World!

Create server.go

package main

import (
	"net/http"
	"github.com/webx-top/echo"
	"github.com/webx-top/echo/engine/standard"
)

func main() {
	e := echo.New()
	e.Get("/", func(c echo.Context) error {
		return c.String("Hello, World!", http.StatusOK)
	})
	e.Run(standard.New(":1323"))
}

Start server

$ go run server.go

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

Routing
e.Post("/users", saveUser)
e.Get("/users/:id", getUser)
e.Put("/users/:id", updateUser)
e.Delete("/users/:id", deleteUser)
Path Parameters
func getUser(c echo.Context) error {
	// User ID from path `users/:id`
	id := c.Param("id")
}
Query Parameters

/show?team=x-men&member=wolverine

func show(c echo.Context) error {
	// Get team and member from the query string
	team := c.Query("team")
	member := c.Query("member")
}
Form application/x-www-form-urlencoded

POST /save

name value
name Joe Smith
email joe@labstack.com
func save(c echo.Context) error {
	// Get name and email
	name := c.Form("name")
	email := c.Form("email")
}
Form multipart/form-data

POST /save

name value
name Joe Smith
email joe@labstack.com
avatar avatar
func save(c echo.Context) error {
	// Get name and email
	name := c.Form("name")
	email := c.Form("email")

	//------------
	// Get avatar
	//------------

	src, fileHeader, err := c.FormFile("avatar")
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	file, err := os.Create(fileHeader.Filename)
	if err != nil {
		return err
	}
	defer file.Close()

	// Copy
	if _, err = io.Copy(file, src); err != nil {
		return err
	}
}
Handling Request
  • Bind JSON or XML payload into Go struct based on Content-Type request header.
  • Render response as JSON or XML with status code.
type User struct {
	Name  string `json:"name" xml:"name"`
	Email string `json:"email" xml:"email"`
}

e.Post("/users", func(c echo.Context) error {
	u := new(User)
	if err := c.MustBind(u); err != nil {
		return err
	}
	return c.JSON(u, http.StatusCreated)
	// or
	// return c.XML(u, http.StatusCreated)
})
Static Content

Server any file from static directory for path /static/*.

e.Use(mw.Static(&mw.StaticOptions{
	Root:"static", //存放静态文件的物理路径
	Path:"/static/", //网址访问静态文件的路径
	Browse:true, //是否在首页显示文件列表
}))
Middleware
// Root level middleware
e.Use(middleware.Log())
e.Use(middleware.Recover())

// Group level middleware
g := e.Group("/admin")
g.Use(middleware.BasicAuth(func(username, password string) bool {
	if username == "joe" && password == "secret" {
		return true
	}
	return false
}))

// Route level middleware
track := func(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		println("request to /users")
		return next.Handle(c)
	}
}
e.Get("/users", func(c echo.Context) error {
	return c.String("/users", http.StatusOK)
}, track)
e.Get("/setcookie", func(c echo.Context) error {
	c.SetCookie("uid","1")
	return c.String("/setcookie: uid="+c.GetCookie("uid"), http.StatusOK)
})
Session
...
import (
	...
	"github.com/webx-top/echo/middleware/session"
	//boltStore "github.com/webx-top/echo/middleware/session/engine/bolt"
	cookieStore "github.com/webx-top/echo/middleware/session/engine/cookie"
)
...
sessionOptions := &echo.SessionOptions{
	Engine: `cookie`,
	Name:   `SESSIONID`,
	CookieOptions: &echo.CookieOptions{
		Path:     `/`,
		Domain:   ``,
		MaxAge:   0,
		Secure:   false,
		HttpOnly: true,
	},
}

cookieStore.RegWithOptions(&cookieStore.CookieOptions{
	KeyPairs: [][]byte{
		[]byte(`123456789012345678901234567890ab`),
	},
	SessionOptions: sessionOptions,
})

e.Use(session.Middleware(sessionOptions))

e.Get("/session", func(c echo.Context) error {
	c.Session().Set("uid",1).Save()
	return c.String(fmt.Sprintf("/session: uid=%v",c.Session().Get("uid")))
})
Websocket
...
import (
	...
	"github.com/admpub/websocket"
	"github.com/webx-top/echo"
	ws "github.com/webx-top/echo/handler/websocket"
)
...

e.HandlerWrapper = ws.HanderWrapper

e.Get("/websocket", func(c *websocket.Conn, ctx echo.Context) error {
	//push(writer)
	go func() {
		var counter int
		for {
			if counter >= 10 { //测试只推10条
				return
			}
			time.Sleep(5 * time.Second)
			message := time.Now().String()
			ctx.Logger().Info(`Push message: `, message)
			if err := c.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
				ctx.Logger().Error(`Push error: `, err.Error())
				return
			}
			counter++
		}
	}()

	//echo
	ws.DefaultExecuter(c, ctx)
	return nil
})

More...

Sockjs
...
import (
	...
	"github.com/webx-top/echo"
	"github.com/admpub/sockjs-go/sockjs"
	ws "github.com/webx-top/echo/handler/sockjs"
)
...

options := ws.Options{
	Handle: func(c sockjs.Session) error {
		//push(writer)
		go func() {
			var counter int
			for {
				if counter >= 10 { //测试只推10条
					return
				}
				time.Sleep(5 * time.Second)
				message := time.Now().String()
				log.Info(`Push message: `, message)
				if err := c.Send(message); err != nil {
					log.Error(`Push error: `, err.Error())
					return
				}
				counter++
			}
		}()

		//echo
		ws.DefaultExecuter(c)
		return nil
	},
	Options: sockjs.DefaultOptions,
	Prefix:  "/websocket",
}
options.Wrapper(e)

More...

Other Example
package main

import (
	"net/http"

	"github.com/webx-top/echo"
	// "github.com/webx-top/echo/engine/fasthttp"
	"github.com/webx-top/echo/engine/standard"
	mw "github.com/webx-top/echo/middleware"
)

func main() {
	e := echo.New()
	e.Use(mw.Log())

	e.Get("/", func(c echo.Context) error {
		return c.String("Hello, World!")
	})
	e.Get("/echo/:name", func(c echo.Context) error {
		return c.String("Echo " + c.Param("name"))
	})
	
	e.Get("/std", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`standard net/http handleFunc`))
		w.WriteHeader(200)
	})

	// FastHTTP
	// e.Run(fasthttp.New(":4444"))

	// Standard
	e.Run(standard.New(":4444"))
}

See other examples...

Middleware list

Middleware Import path Description
BasicAuth github.com/webx-top/echo/middleware HTTP basic authentication
BodyLimit github.com/webx-top/echo/middleware Limit request body
Gzip github.com/webx-top/echo/middleware Send gzip HTTP response
Secure github.com/webx-top/echo/middleware Protection against attacks
CORS github.com/webx-top/echo/middleware Cross-Origin Resource Sharing
CSRF github.com/webx-top/echo/middleware Cross-Site Request Forgery
Log github.com/webx-top/echo/middleware Log HTTP requests
MethodOverride github.com/webx-top/echo/middleware Override request method
Recover github.com/webx-top/echo/middleware Recover from panics
HTTPSRedirect github.com/webx-top/echo/middleware Redirect HTTP requests to HTTPS
HTTPSWWWRedirect github.com/webx-top/echo/middleware Redirect HTTP requests to WWW HTTPS
WWWRedirect github.com/webx-top/echo/middleware Redirect non WWW requests to WWW
NonWWWRedirect github.com/webx-top/echo/middleware Redirect WWW requests to non WWW
AddTrailingSlash github.com/webx-top/echo/middleware Add trailing slash to the request URI
RemoveTrailingSlash github.com/webx-top/echo/middleware Remove trailing slash from the request URI
Static github.com/webx-top/echo/middleware Serve static files
MaxAllowed github.com/webx-top/echo/middleware MaxAllowed limits simultaneous requests; can help with high traffic load
RateLimit github.com/webx-top/echo/middleware/ratelimit Rate limiting HTTP requests
Language github.com/webx-top/echo/middleware/language Multi-language support
Session github.com/webx-top/echo/middleware/session Sessions Manager
JWT github.com/webx-top/echo/middleware/jwt JWT authentication
Hydra github.com/webx-top/echo/middleware/hydra It uses Hydra's API to extract and validate auth token.
Markdown github.com/webx-top/echo/middleware/markdown Markdown rendering
Render github.com/webx-top/echo/middleware/render HTML template rendering
ReverseProxy github.com/webx-top/reverseproxy Reverse proxy

Handler Wrapper list

Wrapper Import path Description
Websocket github.com/webx-top/echo/handler/websocket Example
Sockjs github.com/webx-top/echo/handler/sockjs Example
Oauth2 github.com/webx-top/echo/handler/oauth2 Example
Pprof github.com/webx-top/echo/handler/pprof -

Credits

License

Apache 2

Documentation

Overview

Copyright 2016 Wenhui Shen <www.webx.top>

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2016 Wenhui Shen <www.webx.top>

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

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"

	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"

	CharsetUTF8 = "charset=utf-8"

	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	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"
)

Variables

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

	NotFoundHandler = HandlerFunc(func(c Context) error {
		return ErrNotFound
	})

	MethodNotAllowedHandler = HandlerFunc(func(c Context) error {
		return ErrMethodNotAllowed
	})
)
View Source
var DefaultHtmlFilter = func(v string) (r string) {
	return v
}

Functions

func ContentTypeByExtension

func ContentTypeByExtension(name string) (t string)

ContentTypeByExtension returns the MIME type associated with the file based on its extension. It returns `application/octet-stream` incase MIME type is not found.

func DefaultSkipper

func DefaultSkipper(c Context) bool

defaultSkipper returns false which processes the middleware.

func HandlerName

func HandlerName(h interface{}) string

func Methods

func Methods() []string

func NamedStructMap

func NamedStructMap(e *Echo, m interface{}, data map[string][]string, topName string) error

func SplitJSON

func SplitJSON(s string) ([]string, error)

SplitJSON user[name][test]

Types

type Binder

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

Binder is the interface that wraps the Bind method.

type Context

type Context interface {
	context.Context
	Translator
	Request() engine.Request
	Response() engine.Response
	Path() string
	P(int) string
	Param(string) string

	// ParamNames returns path parameter names.
	ParamNames() []string
	SetParamNames(...string)
	ParamValues() []string
	SetParamValues(values ...string)

	// Queries returns the query parameters as map. It is an alias for `engine.URL#Query()`.
	Queries() map[string][]string
	QueryValues(string) []string
	Query(string) string

	Form(string) string
	FormValues(string) []string

	// Forms returns the form parameters as map. It is an alias for `engine.Request#Form().All()`.
	Forms() map[string][]string

	Set(string, interface{})
	Get(string) interface{}
	Stored() store
	Bind(interface{}) error
	MustBind(interface{}) error
	Render(string, interface{}, ...int) error
	HTML(string, ...int) error
	String(string, ...int) error
	JSON(interface{}, ...int) error
	JSONBlob([]byte, ...int) error
	JSONP(string, interface{}, ...int) error
	XML(interface{}, ...int) error
	XMLBlob([]byte, ...int) error
	File(string) error
	Attachment(io.ReadSeeker, string) error
	NoContent(...int) error
	Redirect(string, ...int) error
	Error(err error)
	Handle(Context) error
	Logger() logger.Logger
	Object() *xContext
	Echo() *Echo

	// ServeContent sends static content from `io.Reader` and handles caching
	// via `If-Modified-Since` request header. It automatically sets `Content-Type`
	// and `Last-Modified` response headers.
	ServeContent(io.ReadSeeker, string, time.Time) error

	SetFunc(string, interface{})
	GetFunc(string) interface{}
	ResetFuncs(map[string]interface{})
	Funcs() map[string]interface{}
	Reset(engine.Request, engine.Response)
	Fetch(string, interface{}) ([]byte, error)
	SetRenderer(Renderer)

	// Cookie
	SetCookieOptions(*CookieOptions)
	CookieOptions() *CookieOptions
	NewCookie(string, string) *Cookie
	Cookie() Cookier
	GetCookie(string) string
	SetCookie(string, string, ...interface{})

	SetSessioner(Sessioner)
	Session() Sessioner
	Flash(string) interface{}

	//with type action
	Px(int) param.String
	Paramx(string) param.String
	Queryx(string) param.String
	Formx(string) param.String
	//string to param.String
	Atop(string) param.String

	SetTranslator(Translator)

	Header(string) string
	IsAjax() bool
	Method() string
	Format() string
	IsPost() bool
	IsGet() bool
	IsPut() bool
	IsDel() bool
	IsHead() bool
	IsPatch() bool
	IsOptions() bool
	IsSecure() bool
	IsWebsocket() bool
	IsUpload() bool
	ResolveContentType() string
	WithFormatExtension(bool)
	ResolveFormat() string
	Protocol() string
	Site() string
	Scheme() string
	Domain() string
	Host() string
	Proxy() []string
	Referer() string
	Port() int
	SetCode(int)
	Code() int
	NewData(...interface{}) *Data
}

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

func NewContext

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

NewContext creates a Context object.

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

func NewCookie

func NewCookie(name string, value string, opts ...*CookieOptions) *Cookie

func (*Cookie) Domain

func (c *Cookie) Domain(p string) *Cookie

func (*Cookie) Expires

func (c *Cookie) Expires(p int64) *Cookie

func (*Cookie) HttpOnly

func (c *Cookie) HttpOnly(p bool) *Cookie

func (*Cookie) MaxAge

func (c *Cookie) MaxAge(p int) *Cookie

func (*Cookie) Path

func (c *Cookie) Path(p string) *Cookie

func (*Cookie) Secure

func (c *Cookie) Secure(p bool) *Cookie

func (*Cookie) Send

func (c *Cookie) Send(ctx Context)

type CookieOptions

type CookieOptions struct {
	Prefix string

	// MaxAge=0 means no 'Max-Age' attribute specified.
	// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
	// MaxAge>0 means Max-Age attribute present and given in seconds.
	MaxAge int

	Path     string
	Domain   string
	Secure   bool
	HttpOnly bool
}

type Cookier

type Cookier interface {
	Get(key string) string
	Set(key string, val string, args ...interface{})
}

func NewCookier

func NewCookier(ctx Context) Cookier

type Data

type Data struct {
	Code int
	Info interface{}
	Zone interface{} `json:",omitempty" xml:",omitempty"`
	Data interface{} `json:",omitempty" xml:",omitempty"`
}

func NewData

func NewData(code int, args ...interface{}) *Data

NewData params: CIZD

func (*Data) Error

func (d *Data) Error() string

func (*Data) SetCode

func (d *Data) SetCode(code int) *Data

func (*Data) SetData

func (d *Data) SetData(data interface{}) *Data

func (*Data) SetInfo

func (d *Data) SetInfo(info interface{}) *Data

func (*Data) SetZone

func (d *Data) SetZone(zone interface{}) *Data

type Echo

type Echo struct {
	HandlerWrapper    func(interface{}) Handler
	MiddlewareWrapper func(interface{}) Middleware
	FuncMap           map[string]interface{}
	// contains filtered or unexported fields
}

func New

func New() (e *Echo)

New creates an instance of Echo.

func NewWithContext

func NewWithContext(fn func(*Echo) Context) (e *Echo)

func (*Echo) Any

func (e *Echo) Any(path string, h interface{}, middleware ...interface{})

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

func (*Echo) AppendRouter

func (e *Echo) AppendRouter(routes []*Route)

AppendRouter append router

func (*Echo) Binder

func (e *Echo) Binder() Binder

Binder returns the binder instance.

func (*Echo) Connect

func (e *Echo) Connect(path string, h interface{}, m ...interface{})

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 interface{}, m ...interface{})

Delete adds a DELETE route > handler to the router.

func (*Echo) Get

func (e *Echo) Get(path string, h interface{}, m ...interface{})

Get adds a GET route > handler to the router.

func (*Echo) Group

func (e *Echo) Group(prefix string, m ...interface{}) (g *Group)

Group creates a new sub-router with prefix.

func (*Echo) Head

func (e *Echo) Head(path string, h interface{}, m ...interface{})

Head adds a HEAD route > handler to the router.

func (*Echo) Logger

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

Logger returns the logger instance.

func (*Echo) Match

func (e *Echo) Match(methods []string, path string, h interface{}, middleware ...interface{})

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

func (*Echo) MetaHandler

func (e *Echo) MetaHandler(m H, handler interface{}) interface{}

Add meta information about endpoint

func (*Echo) MetaMiddleware

func (e *Echo) MetaMiddleware(m H, middleware interface{}) interface{}

Add meta information about endpoint

func (*Echo) NamedRoutes

func (e *Echo) NamedRoutes() map[string][]int

NamedRoutes returns the registered handler name.

func (*Echo) Options

func (e *Echo) Options(path string, h interface{}, m ...interface{})

Options adds an OPTIONS route > handler to the router.

func (*Echo) Patch

func (e *Echo) Patch(path string, h interface{}, m ...interface{})

Patch adds a PATCH route > handler to the router.

func (*Echo) Post

func (e *Echo) Post(path string, h interface{}, m ...interface{})

Post adds a POST route > handler to the router.

func (*Echo) Pre

func (e *Echo) Pre(middleware ...interface{})

Pre is alias

func (*Echo) PreUse

func (e *Echo) PreUse(middleware ...interface{})

PreUse adds handler to the middleware chain.

func (*Echo) Prefix

func (e *Echo) Prefix() string

func (*Echo) Put

func (e *Echo) Put(path string, h interface{}, m ...interface{})

Put adds a PUT route > handler to the router.

func (*Echo) RebuildRouter

func (e *Echo) RebuildRouter(args ...[]*Route)

RebuildRouter rebuild router

func (*Echo) Route

func (e *Echo) Route(methods string, path string, h interface{}, middleware ...interface{})

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(eng engine.Engine)

Run starts the HTTP engine.

func (*Echo) ServeHTTP

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

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(l 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) Stop

func (e *Echo) Stop() error

Stop stops the HTTP server.

func (*Echo) Trace

func (e *Echo) Trace(path string, h interface{}, m ...interface{})

Trace adds a TRACE route > handler to the router.

func (*Echo) URI

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

URI generates a URI from handler.

func (*Echo) URL

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

URL is an alias for `URI` function.

func (*Echo) Use

func (e *Echo) Use(middleware ...interface{})

Use adds handler to the middleware chain.

func (*Echo) ValidHandler

func (e *Echo) ValidHandler(v interface{}) (h Handler)

func (*Echo) ValidMiddleware

func (e *Echo) ValidMiddleware(v interface{}) (m Middleware)

type FromConversion

type FromConversion interface {
	FromString(content string) error
}

FromConversion a struct implements this interface can be convert from request param to a struct

type Group

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

func (*Group) Any

func (g *Group) Any(path string, h interface{}, middleware ...interface{})

func (*Group) Connect

func (g *Group) Connect(path string, h interface{}, m ...interface{})

func (*Group) Delete

func (g *Group) Delete(path string, h interface{}, m ...interface{})

func (*Group) Get

func (g *Group) Get(path string, h interface{}, m ...interface{})

func (*Group) Group

func (g *Group) Group(prefix string, m ...interface{}) *Group

func (*Group) Head

func (g *Group) Head(path string, h interface{}, m ...interface{})

func (*Group) Match

func (g *Group) Match(methods []string, path string, h interface{}, middleware ...interface{})

func (*Group) Options

func (g *Group) Options(path string, h interface{}, m ...interface{})

func (*Group) Patch

func (g *Group) Patch(path string, h interface{}, m ...interface{})

func (*Group) Post

func (g *Group) Post(path string, h interface{}, m ...interface{})

func (*Group) Pre

func (g *Group) Pre(middleware ...interface{})

func (*Group) PreUse

func (g *Group) PreUse(middleware ...interface{})

func (*Group) Prefix

func (g *Group) Prefix() string

func (*Group) Put

func (g *Group) Put(path string, h interface{}, m ...interface{})

func (*Group) Route

func (g *Group) Route(methods string, path string, h interface{}, middleware ...interface{})

func (*Group) SetRenderer

func (g *Group) SetRenderer(r Renderer)

func (*Group) Trace

func (g *Group) Trace(path string, h interface{}, m ...interface{})

func (*Group) URL

func (g *Group) URL(h interface{}, params ...interface{}) string

func (*Group) Use

func (g *Group) Use(middleware ...interface{})

type H

type H map[string]interface{}

func (H) DeepMerge

func (h H) DeepMerge(source H)

func (H) MarshalXML

func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML allows type H to be used with xml.Marshal

func (H) ToData

func (h H) ToData() *Data

ToData conversion to *Data

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

func NewHTTPError

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

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns message.

type HTTPErrorHandler

type HTTPErrorHandler func(error, Context)

HTTPErrorHandler is a centralized HTTP error handler.

type HandleNamer

type HandleNamer interface {
	HandleName() string
}

type Handler

type Handler interface {
	Handle(Context) error
}

func WrapHandler

func WrapHandler(h interface{}) Handler

WrapHandler wrap `interface{}` into `echo.Handler`.

type HandlerFunc

type HandlerFunc func(Context) error

func (HandlerFunc) Handle

func (h HandlerFunc) Handle(c Context) error

func (HandlerFunc) SetMeta

func (h HandlerFunc) SetMeta(e *Echo, meta H) HandlerFunc

type Middleware

type Middleware interface {
	Handle(Handler) Handler
}

func WrapMiddleware

func WrapMiddleware(m interface{}) Middleware

WrapMiddleware wrap `interface{}` into `echo.Middleware`.

func WrapMiddlewareFromHandler

func WrapMiddlewareFromHandler(h HandlerFunc) Middleware

WrapMiddlewareFromHandler wrap `echo.HandlerFunc` into `echo.MiddlewareFunc`.

func WrapMiddlewareFromStdHandleFunc

func WrapMiddlewareFromStdHandleFunc(h func(http.ResponseWriter, *http.Request)) Middleware

func WrapMiddlewareFromStdHandleFuncd

func WrapMiddlewareFromStdHandleFuncd(h func(http.ResponseWriter, *http.Request) error) Middleware

func WrapMiddlewareFromStdHandler

func WrapMiddlewareFromStdHandler(h http.Handler) Middleware

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

func (MiddlewareFunc) Handle

func (m MiddlewareFunc) Handle(h Handler) Handler

func (MiddlewareFunc) SetMeta

func (m MiddlewareFunc) SetMeta(e *Echo, meta H) MiddlewareFunc

type MiddlewareFuncd

type MiddlewareFuncd func(Handler) HandlerFunc

func (MiddlewareFuncd) Handle

func (m MiddlewareFuncd) Handle(h Handler) Handler

func (MiddlewareFuncd) SetMeta

func (m MiddlewareFuncd) SetMeta(e *Echo, meta H) MiddlewareFuncd

type NopSession

type NopSession struct {
}

func (*NopSession) AddFlash

func (n *NopSession) AddFlash(_ interface{}, _ ...string) Sessioner

func (*NopSession) Clear

func (n *NopSession) Clear() Sessioner

func (*NopSession) Delete

func (n *NopSession) Delete(name string) Sessioner

func (*NopSession) Flashes

func (n *NopSession) Flashes(_ ...string) []interface{}

func (*NopSession) Get

func (n *NopSession) Get(name string) interface{}

func (*NopSession) Id

func (n *NopSession) Id() string

func (*NopSession) Options

func (n *NopSession) Options(_ SessionOptions) Sessioner

func (*NopSession) Save

func (n *NopSession) Save() error

func (*NopSession) Set

func (n *NopSession) Set(name string, value interface{}) Sessioner

func (*NopSession) SetId

func (n *NopSession) SetId(id string) Sessioner

type NopTranslate

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

func (*NopTranslate) Lang

func (n *NopTranslate) Lang() string

func (*NopTranslate) T

func (n *NopTranslate) T(format string, args ...interface{}) string

type Renderer

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

Renderer is the interface that wraps the Render method.

type Route

type Route struct {
	Method      string
	Path        string
	Handler     Handler `json:"-" xml:"-"`
	HandlerName string
	Format      string
	Params      []string
	Prefix      string
	Meta        H
}

type Router

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

func NewRouter

func NewRouter(e *Echo) *Router

func (*Router) Add

func (r *Router) Add(method, path string, h Handler, e *Echo) (fpath string, pnames []string)

func (*Router) Find

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

func (*Router) Handle

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

type SessionOptions

type SessionOptions struct {
	Engine string //Store Engine
	Name   string //Session Name
	*CookieOptions
}

Options stores configuration for a session or session store. Fields are a subset of http.Cookie fields.

type Sessioner

type Sessioner interface {
	// Get returns the session value associated to the given key.
	Get(key string) interface{}
	// Set sets the session value associated to the given key.
	Set(key string, val interface{}) Sessioner
	SetId(id string) Sessioner
	Id() string
	// Delete removes the session value associated to the given key.
	Delete(key string) Sessioner
	// Clear deletes all values in the session.
	Clear() Sessioner
	// AddFlash adds a flash message to the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	AddFlash(value interface{}, vars ...string) Sessioner
	// Flashes returns a slice of flash messages from the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	Flashes(vars ...string) []interface{}

	Options(SessionOptions) Sessioner

	// Save saves all sessions used during the current request.
	Save() error
}

Wraps thinly gorilla-session methods. Session stores the values and optional configuration for a session.

var DefaultNopSession Sessioner = &NopSession{}

type Skipper

type Skipper func(c Context) bool

Skipper defines a function to skip middleware. Returning true skips processing the middleware.

type ToConversion

type ToConversion interface {
	ToString() string
}

ToConversion a struct implements this interface can be convert from struct to template variable Not Implemented

type Translator

type Translator interface {
	T(format string, args ...interface{}) string
	Lang() string
}
var DefaultNopTranslate Translator = &NopTranslate{language: `en`}

type Validator

type Validator interface {
	Validate() error
}

Validator is the interface that wraps the Validate method.

Directories

Path Synopsis
handler
jwt
ratelimit/config
Package config provides data structure to configure rate-limiter.
Package config provides data structure to configure rate-limiter.
ratelimit/errors
Package errors provide data structure for errors.
Package errors provide data structure for errors.
render/standard
* * 模板扩展 * @author swh <swh@admpub.com>
* * 模板扩展 * @author swh <swh@admpub.com>

Jump to

Keyboard shortcuts

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