echo

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2019 License: Apache-2.0 Imports: 39 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.

This package need >= go 1.9

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
	//------------
	_, err := c.SaveUploadedFile("avatar","./")
	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`),
	},
})

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.AddHandlerWrapper(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
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 -
MVC github.com/webx-top/echo/handler/mvc Example

Credits

License

Apache 2

Documentation

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"
	MIMEEventStream                      = "text/event-stream"

	CharsetUTF8 = "charset=utf-8"

	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	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"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderCacheControl        = "Cache-Control"

	// Access control
	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"

	FilePathSeparator = string(filepath.Separator)
)
View Source
const SnippetLineNumbers = 13

Variables

View Source
var (
	//DefaultNopFilter 默认过滤器(map->struct)
	DefaultNopFilter FormDataFilter = func(k string, v []string) (string, []string) {
		return k, v
	}
	//DefaultFieldNameFormatter 默认格式化函数(struct->form)
	DefaultFieldNameFormatter FieldNameFormatter = func(topName, fieldName string) string {
		var fName string
		if len(topName) == 0 {
			fName = fieldName
		} else {
			fName = topName + "." + fieldName
		}
		return fName
	}
	//LowerCaseFirstLetter 小写首字母(struct->form)
	LowerCaseFirstLetter FieldNameFormatter = func(topName, fieldName string) string {
		var fName string
		s := []rune(fieldName)
		if len(s) > 0 {
			s[0] = unicode.ToLower(s[0])
			fieldName = string(s)
		}
		if len(topName) == 0 {
			fName = fieldName
		} else {
			fName = topName + "." + fieldName
		}
		return fName
	}
)
View Source
var (
	//States 状态码对应的文本
	States = map[State]*Status{
		-2: {`Non-Privileged`, http.StatusOK},
		-1: {`Unauthenticated`, http.StatusOK},
		0:  {`Failure`, http.StatusOK},
		1:  {`Success`, http.StatusOK},
	}
	//GetStatus 获取状态值
	GetStatus = func(key State) (*Status, bool) {
		v, y := States[key]
		return v, y
	}
)
View Source
var (
	DefaultNopSession     Sessioner = &NopSession{}
	DefaultDebugSession   Sessioner = &DebugSession{}
	DefaultSession                  = DefaultNopSession
	DefaultSessionOptions           = NewSessionOptions(`cookie`, `SID`)
)
View Source
var (
	ErrUnsupportedMediaType        error = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    error = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                error = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   error = NewHTTPError(http.StatusForbidden)
	ErrStatusRequestEntityTooLarge error = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrMethodNotAllowed            error = NewHTTPError(http.StatusMethodNotAllowed)
	ErrRendererNotRegistered             = errors.New("renderer not registered")
	ErrInvalidRedirectCode               = errors.New("invalid redirect status code")
	ErrNotFoundFileInput                 = errors.New("The specified name file input was not found")

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

	MethodNotAllowedHandler = HandlerFunc(func(c Context) error {
		return ErrMethodNotAllowed
	})
)
View Source
var (
	DefaultCookieOptions = &CookieOptions{
		Path: `/`,
	}
)
View Source
var DefaultHTMLFilter = func(v string) (r string) {
	return v
}

DefaultHTMLFilter html filter (`form_filter:"html"`)

Functions

func CaptureTokens added in v1.3.5

func CaptureTokens(pattern *regexp.Regexp, input string) *strings.Replacer

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

func Dump(m interface{}, args ...bool) (r string)

Dump 输出对象和数组的结构信息

func FormNames added in v1.1.0

func FormNames(s string) []string

FormNames user[name][test]

func HandlerName

func HandlerName(h interface{}) string

HandlerName returns the handler name

func HandlerPath added in v1.3.7

func HandlerPath(h interface{}) string

HandlerPath returns the handler path

func HandlerTmpl added in v1.3.7

func HandlerTmpl(handlerPath string) string

func Methods

func Methods() []string

Methods returns methods

func NamedStructMap

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

NamedStructMap 自动将map值映射到结构体

func StructToForm added in v1.1.0

func StructToForm(ctx Context, m interface{}, topName string, fieldNameFormatter FieldNameFormatter)

StructToForm 映射struct到form

func T added in v1.3.9

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

T 标记为多语言文本

func Wd added in v1.3.0

func Wd() string

Types

type Accept added in v1.3.5

type Accept struct {
	Raw     string
	Type    string
	Subtype []string
	Mime    string
	Vendor  []string
}

func NewAccept added in v1.3.5

func NewAccept() *Accept

type Accepts added in v1.3.9

type Accepts struct {
	Raw    string
	Type   []*Accept
	Params param.StringMap
}

func NewAccepts added in v1.3.9

func NewAccepts(accept string) *Accepts

func (*Accepts) Advance added in v1.3.9

func (a *Accepts) Advance() *Accepts

func (*Accepts) Simple added in v1.3.9

func (a *Accepts) Simple(n int) *Accepts

type BaseTransaction added in v1.3.9

type BaseTransaction struct {
	Transaction
	// contains filtered or unexported fields
}

func NewTransaction added in v1.3.9

func NewTransaction(trans Transaction) *BaseTransaction

func (*BaseTransaction) Begin added in v1.3.9

func (b *BaseTransaction) Begin() error

func (*BaseTransaction) Commit added in v1.3.9

func (b *BaseTransaction) Commit() error

func (*BaseTransaction) End added in v1.3.9

func (b *BaseTransaction) End(succeed bool) error

func (*BaseTransaction) Rollback added in v1.3.9

func (b *BaseTransaction) Rollback() error

type Binder

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

Binder is the interface that wraps the Bind method.

func NewBinder added in v1.3.0

func NewBinder(e *Echo) Binder

type Closer added in v1.2.0

type Closer interface {
	Close() error
}

type Context

type Context interface {
	context.Context
	events.Emitter
	SetEmitter(events.Emitter)
	Transaction
	SetTransaction(t Transaction)
	StdContext() context.Context
	SetStdContext(context.Context)
	Validator
	SetValidator(Validator)
	Translator
	SetTranslator(Translator)
	Request() engine.Request
	Response() engine.Response
	Handle(Context) error
	Logger() logger.Logger
	Object() *xContext
	Echo() *Echo
	Route() *Route
	Reset(engine.Request, engine.Response)

	Path() string
	P(int, ...string) string
	Param(string, ...string) string
	// ParamNames returns path parameter names.
	ParamNames() []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
	QueryxValues(string) param.StringSlice
	Query(string, ...string) string

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

	// Param+
	Px(int, ...string) param.String
	Paramx(string, ...string) param.String
	Queryx(string, ...string) param.String
	Formx(string, ...string) param.String
	// string to param.String
	Atop(string) param.String
	ToParamString(string) param.String
	ToStringSlice([]string) param.StringSlice

	Set(string, interface{})
	Get(string, ...interface{}) interface{}
	Delete(...string)
	Stored() Store

	Bind(interface{}, ...FormDataFilter) error
	MustBind(interface{}, ...FormDataFilter) error

	Render(string, interface{}, ...int) error
	HTML(string, ...int) error
	String(string, ...int) error
	Blob([]byte, ...int) error
	JSON(interface{}, ...int) error
	JSONBlob([]byte, ...int) error
	JSONP(string, interface{}, ...int) error
	XML(interface{}, ...int) error
	XMLBlob([]byte, ...int) error
	Stream(func(io.Writer) bool)
	SSEvent(string, chan interface{}) error
	File(string, ...http.FileSystem) error
	Attachment(io.ReadSeeker, string) error
	NoContent(...int) error
	Redirect(string, ...int) error
	Error(err error)
	SetCode(int)
	Code() int
	SetData(Data)
	Data() Data

	// 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{}
	PrintFuncs()

	//----------------
	// Render
	//----------------
	SetAuto(on bool) Context
	Fetch(string, interface{}) ([]byte, error)
	SetRenderer(Renderer)

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

	SetSessionOptions(*SessionOptions)
	SessionOptions() *SessionOptions
	SetSessioner(Sessioner)
	Session() Sessioner
	Flash(...string) interface{}

	Header(string) string
	IsAjax() bool
	IsPjax() bool
	PjaxContainer() string
	Method() string
	Format() string
	SetFormat(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
	Accept() *Accepts
	Protocol() string
	Site() string
	Scheme() string
	Domain() string
	Host() string
	Proxy() []string
	Referer() string
	Port() int
	RealIP() string
	HasAnyRequest() bool

	MapForm(i interface{}, names ...string) error
	MapData(i interface{}, data map[string][]string, names ...string) error
	SaveUploadedFile(fieldName string, saveAbsPath string, saveFileName ...string) (*multipart.FileHeader, error)
	SaveUploadedFileToWriter(string, io.Writer) (*multipart.FileHeader, error)
	//Multiple file upload
	SaveUploadedFiles(fieldName string, savePath func(*multipart.FileHeader) (string, error)) error
	SaveUploadedFilesToWriter(fieldName string, writer func(*multipart.FileHeader) (io.Writer, error)) error

	AddPreResponseHook(func() error) Context
	SetPreResponseHook(...func() error) Context
}

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

type ContextRegister interface {
	SetContext(Context)
}
type Cookie struct {
	// contains filtered or unexported fields
}

Cookie 操作封装

func NewCookie

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

NewCookie create a cookie instance

func (*Cookie) Domain

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

Domain 设置域名

func (*Cookie) Expires

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

Expires 设置过期时间戳

func (*Cookie) HttpOnly

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

HttpOnly 设置是否启用HttpOnly

func (*Cookie) MaxAge

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

MaxAge 设置有效时长(秒)

func (*Cookie) Path

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

Path 设置路径

func (*Cookie) SameSite added in v1.3.9

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

SameSite 设置SameSite

func (*Cookie) Secure

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

Secure 设置是否启用HTTPS

func (*Cookie) Send

func (c *Cookie) Send(ctx Context)

Send 发送cookie数据到响应头

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
	SameSite string // strict / lax
}

CookieOptions cookie options

func (*CookieOptions) Clone added in v1.3.0

func (c *CookieOptions) Clone() *CookieOptions

type Cookier

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

Cookier interface

func NewCookier

func NewCookier(ctx Context) Cookier

NewCookier create a cookie instance

type Data

type Data interface {
	Assign(key string, val interface{})
	Assignx(values *map[string]interface{})
	SetTmplFuncs()
	SetContext(ctx Context) Data
	String() string
	Set(code int, args ...interface{}) Data
	Reset() Data
	SetError(err error, args ...int) Data
	SetCode(code int) Data
	SetURL(url string, args ...int) Data
	SetInfo(info interface{}, args ...int) Data
	SetZone(zone interface{}) Data
	SetData(data interface{}, args ...int) Data
	Gets() (code State, info interface{}, zone interface{}, data interface{})
	GetCode() State
	GetInfo() interface{}
	GetZone() interface{}
	GetData() interface{}
}

Data 响应数据

type DebugSession added in v1.3.5

type DebugSession struct {
}

func (*DebugSession) AddFlash added in v1.3.5

func (n *DebugSession) AddFlash(value interface{}, args ...string) Sessioner

func (*DebugSession) Clear added in v1.3.5

func (n *DebugSession) Clear() Sessioner

func (*DebugSession) Delete added in v1.3.5

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

func (*DebugSession) Flashes added in v1.3.5

func (n *DebugSession) Flashes(args ...string) []interface{}

func (*DebugSession) Get added in v1.3.5

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

func (*DebugSession) ID added in v1.3.5

func (n *DebugSession) ID() string

func (*DebugSession) Options added in v1.3.5

func (n *DebugSession) Options(options SessionOptions) Sessioner

func (*DebugSession) Save added in v1.3.5

func (n *DebugSession) Save() error

func (*DebugSession) Set added in v1.3.5

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

func (*DebugSession) SetID added in v1.3.5

func (n *DebugSession) SetID(id string) Sessioner

type Echo

type Echo struct {
	FuncMap         map[string]interface{}
	RouteDebug      bool
	MiddlewareDebug bool
	JSONPVarName    string
	// 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) AddAcceptFormat added in v1.3.0

func (e *Echo) AddAcceptFormat(mime, format string) *Echo

func (*Echo) AddFormatRenderer added in v1.3.7

func (e *Echo) AddFormatRenderer(format string, renderer func(c Context, data interface{}) error) *Echo

func (*Echo) AddHandlerWrapper added in v1.1.0

func (e *Echo) AddHandlerWrapper(funcs ...func(interface{}) Handler)

func (*Echo) AddMiddlewareWrapper added in v1.1.0

func (e *Echo) AddMiddlewareWrapper(funcs ...func(interface{}) Middleware)

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) Clear added in v1.3.0

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

Clear middleware

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) Engine added in v1.1.0

func (e *Echo) Engine() engine.Engine

func (*Echo) File added in v1.3.0

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

File registers a new route with path to serve a static file.

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{}) *Group

Group creates a new sub-router with prefix.

func (*Echo) HTTPErrorHandler added in v1.3.0

func (e *Echo) HTTPErrorHandler() HTTPErrorHandler

HTTPErrorHandler returns the HTTPErrorHandler

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{}) Handler

MetaHandler 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) ParseHeaderAccept added in v1.3.9

func (e *Echo) ParseHeaderAccept(on bool) *Echo

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 an alias for `PreUse` function.

func (*Echo) PreUse

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

PreUse adds handler to the middleware chain.

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) RemoveFormatRenderer added in v1.3.7

func (e *Echo) RemoveFormatRenderer(formats ...string) *Echo

func (*Echo) Renderer added in v1.3.0

func (e *Echo) Renderer() Renderer

Renderer returns the renderer instance.

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, handler ...engine.Handler) error

Run starts the HTTP engine.

func (*Echo) ServeHTTP

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

func (*Echo) SetAcceptFormats added in v1.3.0

func (e *Echo) SetAcceptFormats(acceptFormats map[string]string) *Echo

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) SetFormatRenderers added in v1.3.7

func (e *Echo) SetFormatRenderers(formatRenderers map[string]func(c Context, data interface{}) error) *Echo

func (*Echo) SetHTTPErrorHandler

func (e *Echo) SetHTTPErrorHandler(h HTTPErrorHandler)

SetHTTPErrorHandler registers a custom Echo.HTTPErrorHandler.

func (*Echo) SetHandlerWrapper added in v1.1.0

func (e *Echo) SetHandlerWrapper(funcs ...func(interface{}) Handler)

func (*Echo) SetLogger

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

SetLogger sets the logger instance.

func (*Echo) SetMiddlewareWrapper added in v1.1.0

func (e *Echo) SetMiddlewareWrapper(funcs ...func(interface{}) Middleware)

func (*Echo) SetRenderer

func (e *Echo) SetRenderer(r Renderer)

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

func (*Echo) Static added in v1.3.0

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

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

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

type FieldNameFormatter func(topName, fieldName string) string

FieldNameFormatter 结构体字段值映射到表单时,结构体字段名称格式化处理

type FormDataFilter added in v1.1.0

type FormDataFilter func(key string, values []string) (string, []string)

FormDataFilter 将map映射到结构体时,对名称和值的过滤处理,如果返回的名称为空,则跳过本字段

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) Echo added in v1.3.5

func (g *Group) Echo() *Echo

func (*Group) File added in v1.3.0

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

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

func (*Group) Get

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

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...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) MetaHandler added in v1.3.5

func (g *Group) MetaHandler(m H, handler interface{}) Handler

MetaHandler Add meta information about endpoint

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{})

Pre is an alias for `PreUse` function.

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) Static added in v1.3.0

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

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

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 = Store

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

type ICore added in v1.1.0

type ICore interface {
	RouteRegister
	MiddlewareRegister
	URLBuilder
}

type KV added in v1.1.1

type KV struct {
	K string
	V string
}

KV 键值对

type KVData added in v1.1.1

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

KVData 键值对数据(保持顺序)

func NewKVData added in v1.1.1

func NewKVData() *KVData

NewKVData 键值对数据

func (*KVData) Add added in v1.1.1

func (a *KVData) Add(k, v string) *KVData

Add 添加键值

func (*KVData) Delete added in v1.1.1

func (a *KVData) Delete(ks ...string) *KVData

Delete 设置某个键的所有值

func (*KVData) Get added in v1.3.5

func (a *KVData) Get(k string) string

func (*KVData) Has added in v1.3.5

func (a *KVData) Has(k string) bool

func (*KVData) Index added in v1.1.1

func (a *KVData) Index(k string) []int

Index 返回某个key的所有索引值

func (*KVData) Indexes added in v1.1.1

func (a *KVData) Indexes() map[string][]int

Indexes 返回所有索引值

func (*KVData) Reset added in v1.1.1

func (a *KVData) Reset() *KVData

Reset 重置

func (*KVData) Set added in v1.1.1

func (a *KVData) Set(k, v string) *KVData

Set 设置首个键值

func (*KVData) Slice added in v1.1.1

func (a *KVData) Slice() []*KV

Slice 返回切片

type KVList added in v1.3.5

type KVList []*KV

func (*KVList) Add added in v1.3.5

func (list *KVList) Add(k, v string)

func (*KVList) Del added in v1.3.5

func (list *KVList) Del(i int)

func (*KVList) Reset added in v1.3.5

func (list *KVList) Reset()

type Mapx added in v1.1.1

type Mapx struct {
	Map   map[string]*Mapx `json:",omitempty"`
	Slice []*Mapx          `json:",omitempty"`
	Val   []string         `json:",omitempty"`
	// contains filtered or unexported fields
}

func NewMapx added in v1.1.1

func NewMapx(data map[string][]string, mutex ...*sync.RWMutex) *Mapx

func (*Mapx) Add added in v1.3.6

func (m *Mapx) Add(name string, values []string) *Mapx

func (*Mapx) AsFlatSlice added in v1.4.0

func (m *Mapx) AsFlatSlice() []string

func (*Mapx) AsMap added in v1.4.0

func (m *Mapx) AsMap() map[string]interface{}

func (*Mapx) AsSlice added in v1.4.0

func (m *Mapx) AsSlice() []interface{}

func (*Mapx) AsStore added in v1.4.0

func (m *Mapx) AsStore() Store

func (*Mapx) Clone added in v1.3.6

func (m *Mapx) Clone() *Mapx

func (*Mapx) Get added in v1.1.1

func (m *Mapx) Get(names ...string) *Mapx

func (*Mapx) IsMap added in v1.4.0

func (m *Mapx) IsMap() bool

func (*Mapx) IsSlice added in v1.4.0

func (m *Mapx) IsSlice() bool

func (*Mapx) Parse added in v1.1.1

func (m *Mapx) Parse(data map[string][]string, keySkipper ...func(string) bool) *Mapx

func (*Mapx) Value added in v1.1.1

func (m *Mapx) Value(names ...string) string

func (*Mapx) ValueOk added in v1.1.1

func (m *Mapx) ValueOk(names ...string) (string, bool)

func (*Mapx) Values added in v1.1.1

func (m *Mapx) Values(names ...string) []string

func (*Mapx) ValuesOk added in v1.1.1

func (m *Mapx) ValuesOk(names ...string) ([]string, bool)

type Meta added in v1.2.0

type Meta interface {
	Meta() H
}

type MetaHandler added in v1.3.0

type MetaHandler struct {
	Handler
	// contains filtered or unexported fields
}

func (*MetaHandler) Meta added in v1.3.0

func (m *MetaHandler) Meta() H

func (*MetaHandler) Name added in v1.3.5

func (m *MetaHandler) Name() string

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

func WrapMiddlewareFromStdHandleFunc

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

WrapMiddlewareFromStdHandleFunc wrap `func(http.ResponseWriter, *http.Request)` into `echo.Middleware`.

func WrapMiddlewareFromStdHandleFuncd

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

WrapMiddlewareFromStdHandleFuncd wrap `func(http.ResponseWriter, *http.Request)` into `echo.Middleware`.

func WrapMiddlewareFromStdHandler

func WrapMiddlewareFromStdHandler(h http.Handler) Middleware

WrapMiddlewareFromStdHandler wrap `http.HandlerFunc` into `echo.Middleware`.

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

func (MiddlewareFunc) Handle

func (m MiddlewareFunc) Handle(h Handler) Handler

type MiddlewareFuncd

type MiddlewareFuncd func(Handler) HandlerFunc

func (MiddlewareFuncd) Handle

func (m MiddlewareFuncd) Handle(h Handler) Handler

type MiddlewareRegister added in v1.1.0

type MiddlewareRegister interface {
	Use(middleware ...interface{})
	Pre(middleware ...interface{})
}

type Name added in v1.3.5

type Name interface {
	Name() string
}

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

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

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

type NopTransaction added in v1.3.9

type NopTransaction struct {
}

func (*NopTransaction) Begin added in v1.3.9

func (b *NopTransaction) Begin() error

func (*NopTransaction) Commit added in v1.3.9

func (b *NopTransaction) Commit() error

func (*NopTransaction) End added in v1.3.9

func (b *NopTransaction) End(succeed bool) error

func (*NopTransaction) Rollback added in v1.3.9

func (b *NopTransaction) Rollback() error

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

type NopValidation struct {
}

func (*NopValidation) Validate added in v1.2.0

func (v *NopValidation) Validate(_ interface{}, _ ...string) ValidateResult

type PanicError added in v1.3.0

type PanicError struct {
	Raw      interface{}
	Traces   []*Trace
	Snippets []*SnippetGroup
	// contains filtered or unexported fields
}

func NewPanicError added in v1.3.0

func NewPanicError(recovered interface{}, err error) *PanicError

func (*PanicError) AddTrace added in v1.3.0

func (p *PanicError) AddTrace(trace *Trace) *PanicError

func (*PanicError) Debug added in v1.3.0

func (p *PanicError) Debug() bool

func (*PanicError) Error added in v1.3.0

func (p *PanicError) Error() string

func (*PanicError) ExtractSnippets added in v1.3.0

func (p *PanicError) ExtractSnippets(file string, curLineNum int, index int) error

func (*PanicError) HTML added in v1.3.0

func (p *PanicError) HTML() template.HTML

func (*PanicError) JSONString added in v1.3.0

func (p *PanicError) JSONString() string

func (*PanicError) SetDebug added in v1.3.0

func (p *PanicError) SetDebug(on bool) *PanicError

func (*PanicError) SetError added in v1.3.0

func (p *PanicError) SetError(err error) *PanicError

func (*PanicError) SetErrorString added in v1.3.0

func (p *PanicError) SetErrorString(errStr string) *PanicError

func (*PanicError) String added in v1.3.0

func (p *PanicError) String() string

type Prefixer added in v1.3.5

type Prefixer interface {
	Prefix() string
}

type RawData added in v1.3.0

type RawData struct {
	Code  State
	State string `json:",omitempty" xml:",omitempty"`
	Info  interface{}
	URL   string      `json:",omitempty" xml:",omitempty"`
	Zone  interface{} `json:",omitempty" xml:",omitempty"`
	Data  interface{} `json:",omitempty" xml:",omitempty"`
	// contains filtered or unexported fields
}

func NewData

func NewData(ctx Context) *RawData

func (*RawData) Assign added in v1.3.0

func (d *RawData) Assign(key string, val interface{})

Assign 赋值

func (*RawData) Assignx added in v1.3.0

func (d *RawData) Assignx(values *map[string]interface{})

Assignx 批量赋值

func (*RawData) Error added in v1.3.0

func (d *RawData) Error() string

func (*RawData) GetCode added in v1.3.0

func (d *RawData) GetCode() State

func (*RawData) GetData added in v1.3.0

func (d *RawData) GetData() interface{}

GetData 获取数据

func (*RawData) GetInfo added in v1.3.0

func (d *RawData) GetInfo() interface{}

func (*RawData) GetZone added in v1.3.0

func (d *RawData) GetZone() interface{}

func (*RawData) Gets added in v1.3.0

func (d *RawData) Gets() (State, interface{}, interface{}, interface{})

Gets 获取全部数据

func (*RawData) Reset added in v1.3.0

func (d *RawData) Reset() Data

func (*RawData) Set added in v1.3.0

func (d *RawData) Set(code int, args ...interface{}) Data

Set 设置输出(code,info,zone,RawData)

func (*RawData) SetCode added in v1.3.0

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

SetCode 设置状态码

func (*RawData) SetContext added in v1.3.0

func (d *RawData) SetContext(ctx Context) Data

SetContext 设置Context

func (*RawData) SetData added in v1.3.0

func (d *RawData) SetData(data interface{}, args ...int) Data

SetData 设置正常数据

func (*RawData) SetError added in v1.3.0

func (d *RawData) SetError(err error, args ...int) Data

SetError 设置错误

func (*RawData) SetInfo added in v1.3.0

func (d *RawData) SetInfo(info interface{}, args ...int) Data

SetInfo 设置提示信息

func (*RawData) SetTmplFuncs added in v1.3.0

func (d *RawData) SetTmplFuncs()

SetTmplFuncs 设置模板函数

func (*RawData) SetURL added in v1.3.9

func (d *RawData) SetURL(url string, args ...int) Data

SetURL 设置跳转网址

func (*RawData) SetZone added in v1.3.0

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

SetZone 设置提示区域

func (*RawData) String added in v1.3.0

func (d *RawData) String() 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 //param names
	Prefix      string
	Meta        H
	// contains filtered or unexported fields
}

func (*Route) IsZero added in v1.3.0

func (r *Route) IsZero() bool

type RouteRegister added in v1.1.0

type RouteRegister interface {
	Any(path string, h interface{}, middleware ...interface{})
	Route(methods string, path string, h interface{}, middleware ...interface{})
	Match(methods []string, path string, h interface{}, middleware ...interface{})
	Connect(path string, h interface{}, m ...interface{})
	Delete(path string, h interface{}, m ...interface{})
	Get(path string, h interface{}, m ...interface{})
	Head(path string, h interface{}, m ...interface{})
	Options(path string, h interface{}, m ...interface{})
	Patch(path string, h interface{}, m ...interface{})
	Post(path string, h interface{}, m ...interface{})
	Put(path string, h interface{}, m ...interface{})
	Trace(path string, h interface{}, m ...interface{})
	Static(prefix, root string)
	File(path, file string)
}

type Router

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

func NewRouter

func NewRouter(e *Echo) *Router

func (*Router) Add

func (r *Router) Add(rt *Route, rid int)

Add 添加路由 method: 方法(GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD/CONNECT/TRACE) prefix: group前缀 path: 路径(含前缀) h: Handler name: Handler名 meta: meta数据

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
}

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

func NewSessionOptions added in v1.4.0

func NewSessionOptions(engine string, name string, args ...*CookieOptions) *SessionOptions

func (*SessionOptions) Clone added in v1.3.0

func (s *SessionOptions) Clone() *SessionOptions

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{}
	// Save saves all sessions used during the current request.
	Save() error
}

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

type Skipper

type Skipper func(c Context) bool

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

type Snippet added in v1.3.0

type Snippet struct {
	Number  int
	Code    string
	Current bool
}

type SnippetGroup added in v1.3.0

type SnippetGroup struct {
	Path    string
	Index   int
	Snippet []*Snippet
}

func (*SnippetGroup) String added in v1.3.0

func (sg *SnippetGroup) String() string

func (*SnippetGroup) TableRow added in v1.3.0

func (sg *SnippetGroup) TableRow() string

type State added in v1.2.0

type State int

State 状态码类型

func (State) HTTPCode added in v1.3.0

func (s State) HTTPCode() int

HTTPCode 返回HTTP状态码

func (State) Int added in v1.2.0

func (s State) Int() int

Int 返回int类型的自定义状态码

func (State) String added in v1.2.0

func (s State) String() string

type Status added in v1.3.0

type Status struct {
	Text string
	Code int
}

Status 状态值

type Store added in v1.3.7

type Store map[string]interface{}

func (Store) Bool added in v1.3.7

func (s Store) Bool(key string, defaults ...interface{}) bool

func (Store) CSS added in v1.3.7

func (s Store) CSS(key string, defaults ...interface{}) template.CSS

func (Store) Children added in v1.4.0

func (s Store) Children(keys ...interface{}) Store

func (Store) Clone added in v1.3.8

func (s Store) Clone() Store

func (Store) DateTime added in v1.4.0

func (s Store) DateTime(key string, layouts ...string) time.Time

func (Store) Decr added in v1.3.7

func (s Store) Decr(key string, n int64, defaults ...interface{}) int64

func (Store) DeepMerge added in v1.3.8

func (s Store) DeepMerge(source Store)

func (Store) Delete added in v1.3.7

func (s Store) Delete(keys ...string)

func (Store) Float32 added in v1.3.7

func (s Store) Float32(key string, defaults ...interface{}) float32

func (Store) Float64 added in v1.3.7

func (s Store) Float64(key string, defaults ...interface{}) float64

func (Store) Get added in v1.3.7

func (s Store) Get(key string, defaults ...interface{}) interface{}

func (Store) HTML added in v1.3.7

func (s Store) HTML(key string, defaults ...interface{}) template.HTML

func (Store) HTMLAttr added in v1.3.7

func (s Store) HTMLAttr(key string, defaults ...interface{}) template.HTMLAttr

func (Store) Has added in v1.4.0

func (s Store) Has(key string) bool

func (Store) Incr added in v1.3.7

func (s Store) Incr(key string, n int64, defaults ...interface{}) int64

func (Store) Int added in v1.3.7

func (s Store) Int(key string, defaults ...interface{}) int

func (Store) Int16 added in v1.3.7

func (s Store) Int16(key string, defaults ...interface{}) int16

func (Store) Int32 added in v1.3.7

func (s Store) Int32(key string, defaults ...interface{}) int32

func (Store) Int64 added in v1.3.7

func (s Store) Int64(key string, defaults ...interface{}) int64

func (Store) Int8 added in v1.3.7

func (s Store) Int8(key string, defaults ...interface{}) int8

func (Store) JS added in v1.3.7

func (s Store) JS(key string, defaults ...interface{}) template.JS

func (Store) MarshalXML added in v1.3.8

func (s Store) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML allows type Store to be used with xml.Marshal

func (Store) Set added in v1.3.7

func (s Store) Set(key string, value interface{}) Store

func (Store) Split added in v1.4.0

func (s Store) Split(key string, sep string, limit ...int) param.StringSlice

func (Store) Store added in v1.3.9

func (s Store) Store(key string, defaults ...interface{}) Store

func (Store) String added in v1.3.7

func (s Store) String(key string, defaults ...interface{}) string

func (Store) Timestamp added in v1.4.0

func (s Store) Timestamp(key string, defaults ...interface{}) time.Time

func (Store) ToData added in v1.3.8

func (s Store) ToData() *RawData

ToData conversion to *RawData

func (Store) Trim added in v1.4.0

func (s Store) Trim(key string, defaults ...interface{}) param.String

func (Store) Uint added in v1.3.7

func (s Store) Uint(key string, defaults ...interface{}) uint

func (Store) Uint16 added in v1.3.7

func (s Store) Uint16(key string, defaults ...interface{}) uint16

func (Store) Uint32 added in v1.3.7

func (s Store) Uint32(key string, defaults ...interface{}) uint32

func (Store) Uint64 added in v1.3.7

func (s Store) Uint64(key string, defaults ...interface{}) uint64

func (Store) Uint8 added in v1.3.7

func (s Store) Uint8(key string, defaults ...interface{}) uint8

type ToConversion

type ToConversion interface {
	ToString() string
}

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

type Trace added in v1.3.0

type Trace struct {
	Line   int
	File   string
	Func   string
	HasErr bool
}

type Transaction added in v1.3.9

type Transaction interface {
	Begin() error
	Rollback() error
	Commit() error
	End(succeed bool) error
}
var (
	DefaultNopTransaction Transaction = &NopTransaction{}
)

type Translator

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

type URLBuilder added in v1.1.0

type URLBuilder interface {
	URL(interface{}, ...interface{}) string
}

type ValidateResult added in v1.3.0

type ValidateResult interface {
	Ok() bool
	Error() error
	Field() string
	Raw() interface{}

	//setter
	SetError(error) ValidateResult
	SetField(string) ValidateResult
	SetRaw(interface{}) ValidateResult
}

func NewValidateResult added in v1.3.0

func NewValidateResult() ValidateResult

type Validation added in v1.2.0

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

func (*Validation) Validate added in v1.2.0

func (v *Validation) Validate(i interface{}, args ...string) ValidateResult

Validate 此处支持两种用法: 1. Validate(表单字段名, 表单值, 验证规则名) 2. Validate(结构体实例, 要验证的结构体字段1,要验证的结构体字段2) Validate(结构体实例) 代表验证所有带“valid”标签的字段

type Validator

type Validator interface {
	Validate(i interface{}, args ...string) ValidateResult
}

Validator is the interface that wraps the Validate method.

var (
	DefaultNopValidate Validator = &NopValidation{}

	ErrNoSetValidator = errors.New(`The validator is not set`)
)

func NewValidation added in v1.2.0

func NewValidation() Validator

type ValidatorResult added in v1.3.0

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

func (*ValidatorResult) Error added in v1.3.0

func (v *ValidatorResult) Error() error

func (*ValidatorResult) Field added in v1.3.0

func (v *ValidatorResult) Field() string

func (*ValidatorResult) Ok added in v1.3.0

func (v *ValidatorResult) Ok() bool

func (*ValidatorResult) Raw added in v1.3.0

func (v *ValidatorResult) Raw() interface{}

func (*ValidatorResult) SetError added in v1.3.0

func (v *ValidatorResult) SetError(err error) ValidateResult

func (*ValidatorResult) SetField added in v1.3.0

func (v *ValidatorResult) SetField(field string) ValidateResult

func (*ValidatorResult) SetRaw added in v1.3.0

func (v *ValidatorResult) SetRaw(raw interface{}) ValidateResult

Directories

Path Synopsis
encoding
handler
mvc
mvc/static/minify
Package cssmin minifies CSS.
Package cssmin minifies CSS.
jwt
ratelimit/config
Package config provides data structure to configure rate-limiter.
Package config provides data structure to configure rate-limiter.
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