echo

package module
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2019 License: Apache-2.0 Imports: 39 Imported by: 0

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

Cases

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
	StackSize          = 4 << 10 // 4 KB
)

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
	}
	//DateToTimestamp 日期时间转时间戳
	DateToTimestamp = func(layouts ...string) FormDataFilter {
		layout := `2006-01-02`
		if len(layouts) > 0 && len(layouts[0]) > 0 {
			layout = layouts[0]
		}
		return func(k string, v []string) (string, []string) {
			if len(v) > 0 && len(v[0]) > 0 {
				t, e := time.Parse(layout, v[0])
				if e != nil {
					log.Error(e)
					return k, []string{`0`}
				}
				return k, []string{fmt.Sprint(t.Unix())}
			}
			return k, []string{`0`}
		}
	}
	//TimestampToDate 时间戳转日期时间
	TimestampToDate = func(layouts ...string) FormDataFilter {
		layout := `2006-01-02 15:04:05`
		if len(layouts) > 0 && len(layouts[0]) > 0 {
			layout = layouts[0]
		}
		return func(k string, v []string) (string, []string) {
			if len(v) > 0 && len(v[0]) > 0 {
				tsi := strings.SplitN(v[0], `.`, 2)
				var sec, nsec int64
				switch len(tsi) {
				case 2:
					nsec = param.AsInt64(tsi[1])
					fallthrough
				case 1:
					sec = param.AsInt64(tsi[0])
				}
				t := time.Unix(sec, nsec)
				if t.IsZero() {
					return k, []string{``}
				}
				return k, []string{t.Format(layout)}
			}
			return k, v
		}
	}
	//JoinValues 组合数组为字符串
	JoinValues = func(seperators ...string) FormDataFilter {
		sep := `,`
		if len(seperators) > 0 {
			sep = seperators[0]
		}
		return func(k string, v []string) (string, []string) {
			return k, []string{strings.Join(v, sep)}
		}
	}
	//SplitValues 拆分字符串为数组
	SplitValues = func(seperators ...string) FormDataFilter {
		sep := `,`
		if len(seperators) > 0 {
			sep = seperators[0]
		}
		return func(k string, v []string) (string, []string) {
			if len(v) > 0 && len(v[0]) > 0 {
				v = strings.Split(v[0], sep)
			}
			return k, v
		}
	}
)
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 AsStore = param.AsStore
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 Bool

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

func CSS

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

func CaptureTokens

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 DateTime

func DateTime(key interface{}, layouts ...string) time.Time

func Decr

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

func DefaultSkipper

func DefaultSkipper(c Context) bool

DefaultSkipper returns false which processes the middleware.

func Delete

func Delete(key interface{})

func Dump

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

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

func E

func E(format string, args ...interface{}) error

func Float32

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

func Float64

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

func FormNames

func FormNames(s string) []string

FormNames user[name][test]

func Get

func Get(key interface{}, defaults ...interface{}) interface{}

func GetOk

func GetOk(key interface{}) (interface{}, bool)

func GetOrSet

func GetOrSet(key, value interface{}) (actual interface{}, loaded bool)

func HTML

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

func HTMLAttr

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

func HandlerName

func HandlerName(h interface{}) string

HandlerName returns the handler name

func HandlerPath

func HandlerPath(h interface{}) string

HandlerPath returns the handler path

func HandlerTmpl

func HandlerTmpl(handlerPath string) string

func Has

func Has(key interface{}) bool

func Incr

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

func Int

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

func Int16

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

func Int32

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

func Int64

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

func Int8

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

func JS

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

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 NewHost

func NewHost(name string) *host

func Range

func Range(f func(key, value interface{}) bool)

func Set

func Set(key, value interface{})

func SetFormValue

func SetFormValue(f engine.URLValuer, fName string, index int, value interface{})

func SetWorkDir

func SetWorkDir(dir string)

func Split

func Split(key interface{}, sep string, limit ...int) param.StringSlice

func String

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

func StructToForm

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

StructToForm 映射struct到form

func T

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

T 标记为多语言文本

func Timestamp

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

func Trim

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

func Uint

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

func Uint16

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

func Uint32

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

func Uint64

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

func Uint8

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

func Wd

func Wd() string

Types

type Accept

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

func NewAccept

func NewAccept() *Accept

type Accepts

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

func NewAccepts

func NewAccepts(accept string) *Accepts

func (*Accepts) Advance

func (a *Accepts) Advance() *Accepts

func (*Accepts) Simple

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

type AsMiddleware

type AsMiddleware func(Context) error

func (AsMiddleware) Handle

func (m AsMiddleware) Handle(h Handler) Handler

type BaseTransaction

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

func NewTransaction

func NewTransaction(trans Transaction) *BaseTransaction

func (*BaseTransaction) Begin

func (b *BaseTransaction) Begin(ctx context.Context) error

func (*BaseTransaction) Commit

func (b *BaseTransaction) Commit(ctx context.Context) error

func (*BaseTransaction) End

func (b *BaseTransaction) End(ctx context.Context, succeed bool) error

func (*BaseTransaction) Rollback

func (b *BaseTransaction) Rollback(ctx context.Context) 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

func NewBinder(e *Echo) Binder

type Closer

type Closer interface {
	Close() error
}

type Context

type Context interface {
	context.Context
	events.Emitter
	SetEmitter(events.Emitter)

	//Transaction
	SetTransaction(t Transaction)
	Transaction() Transaction
	Begin() error
	Rollback() error
	Commit() error
	End(succeed bool) error

	//Standard Context
	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)
	// Host
	HostNames() []string
	HostValues() []string
	HostParam(string, ...string) string
	HostP(int, ...string) 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
	Internal() *param.SafeMap

	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.Reader, string, ...bool) 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
	// contains filtered or unexported methods
}

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

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 int) *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

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

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
	SetByMap(Store) 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{}
	GetURL() string
}

Data 响应数据

type DebugSession

type DebugSession struct {
}

func (*DebugSession) AddFlash

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

func (*DebugSession) Clear

func (n *DebugSession) Clear() Sessioner

func (*DebugSession) Delete

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

func (*DebugSession) Flashes

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

func (*DebugSession) Get

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

func (*DebugSession) ID

func (n *DebugSession) ID() string

func (*DebugSession) Options

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

func (*DebugSession) Save

func (n *DebugSession) Save() error

func (*DebugSession) Set

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

func (*DebugSession) SetID

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

type DebugTransaction

type DebugTransaction struct {
}

func (*DebugTransaction) Begin

func (b *DebugTransaction) Begin(ctx context.Context) error

func (*DebugTransaction) Commit

func (b *DebugTransaction) Commit(ctx context.Context) error

func (*DebugTransaction) End

func (b *DebugTransaction) End(ctx context.Context, succeed bool) error

func (*DebugTransaction) Rollback

func (b *DebugTransaction) Rollback(ctx context.Context) error

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

func (e *Echo) Add(method, path string, handler interface{}, middleware ...interface{}) *Route

Add registers a new route for an HTTP method and path with matching handler in the router with optional route-level middleware.

func (*Echo) AddAcceptFormat

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

func (*Echo) AddFormatRenderer

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

func (*Echo) AddHandlerWrapper

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

func (*Echo) AddMiddlewareWrapper

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

func (*Echo) Any

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

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

func (*Echo) AppendRouter

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

AppendRouter append router

func (*Echo) Binder

func (e *Echo) Binder() Binder

Binder returns the binder instance.

func (*Echo) Clear

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

Clear middleware

func (*Echo) Commit

func (e *Echo) Commit() *Echo

func (*Echo) Connect

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

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

Delete adds a DELETE route > handler to the router.

func (*Echo) Engine

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

func (*Echo) File

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

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

func (e *Echo) HTTPErrorHandler() HTTPErrorHandler

HTTPErrorHandler returns the HTTPErrorHandler

func (*Echo) Head

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

Head adds a HEAD route > handler to the router.

func (*Echo) Host

func (e *Echo) Host(name string, m ...interface{}) *Group

Host creates a new router group for the provided host and optional host-level middleware.

func (*Echo) Hosts

func (e *Echo) Hosts() map[string]*Host

Hosts returns the map of host => Host.

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

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

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

func (*Echo) Options

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

Options adds an OPTIONS route > handler to the router.

func (*Echo) ParseHeaderAccept

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

func (*Echo) Patch

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

Patch adds a PATCH route > handler to the router.

func (*Echo) Post

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

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

func (e *Echo) Prefix() string

func (*Echo) Put

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

Put adds a PUT route > handler to the router.

func (*Echo) RebuildRouter

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

RebuildRouter rebuild router

func (*Echo) RemoveFormatRenderer

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

func (*Echo) Renderer

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

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

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

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

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

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

func (*Echo) SetPrefix

func (e *Echo) SetPrefix(prefix string) *Echo

func (*Echo) SetRenderer

func (e *Echo) SetRenderer(r Renderer)

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

func (*Echo) Static

func (e *Echo) Static(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{}) IRouter

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

type FieldNameFormatter func(topName, fieldName string) string

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

type FormDataFilter

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

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

func ExcludeFieldName

func ExcludeFieldName(fieldNames ...string) FormDataFilter

ExcludeFieldName 排除字段

func FormatFieldValue

func FormatFieldValue(formatters map[string]FormDataFilter) FormDataFilter

FormatFieldValue 格式化字段值

func IncludeFieldName

func IncludeFieldName(fieldNames ...string) FormDataFilter

IncludeFieldName 包含字段

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

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

func (*Group) Any

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

func (*Group) Connect

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

func (*Group) Delete

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

func (*Group) Echo

func (g *Group) Echo() *Echo

func (*Group) File

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

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

func (*Group) Match

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

func (*Group) MetaHandler

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

func (*Group) Patch

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

func (*Group) Post

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

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

func (*Group) Route

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

func (*Group) SetRenderer

func (g *Group) SetRenderer(r Renderer)

func (*Group) Static

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

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 Host

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

type IRouter

type IRouter interface {
	SetName(string) IRouter
}

type KV

type KV struct {
	K string
	V string
}

KV 键值对

type KVData

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

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

func NewKVData

func NewKVData() *KVData

NewKVData 键值对数据

func (*KVData) Add

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

Add 添加键值

func (*KVData) Delete

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

Delete 设置某个键的所有值

func (*KVData) Get

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

func (*KVData) Has

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

func (*KVData) Index

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

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

func (*KVData) Indexes

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

Indexes 返回所有索引值

func (*KVData) Reset

func (a *KVData) Reset() *KVData

Reset 重置

func (*KVData) Set

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

Set 设置首个键值

func (*KVData) Slice

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

Slice 返回切片

type KVList

type KVList []*KV

func (*KVList) Add

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

func (*KVList) Del

func (list *KVList) Del(i int)

func (*KVList) Reset

func (list *KVList) Reset()

type Mapx

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

func NewMapx

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

func (*Mapx) Add

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

func (*Mapx) AsFlatSlice

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

func (*Mapx) AsMap

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

func (*Mapx) AsSlice

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

func (*Mapx) AsStore

func (m *Mapx) AsStore() Store

func (*Mapx) Clone

func (m *Mapx) Clone() *Mapx

func (*Mapx) Get

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

func (*Mapx) IsMap

func (m *Mapx) IsMap() bool

func (*Mapx) IsSlice

func (m *Mapx) IsSlice() bool

func (*Mapx) Parse

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

func (*Mapx) Value

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

func (*Mapx) ValueOk

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

func (*Mapx) Values

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

func (*Mapx) ValuesOk

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

type Meta

type Meta interface {
	Meta() H
}

type MetaHandler

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

func (*MetaHandler) Meta

func (m *MetaHandler) Meta() H

func (*MetaHandler) Name

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

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

type Name

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

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 NopTransaction

type NopTransaction struct {
}

func (*NopTransaction) Begin

func (b *NopTransaction) Begin(ctx context.Context) error

func (*NopTransaction) Commit

func (b *NopTransaction) Commit(ctx context.Context) error

func (*NopTransaction) End

func (b *NopTransaction) End(ctx context.Context, succeed bool) error

func (*NopTransaction) Rollback

func (b *NopTransaction) Rollback(ctx context.Context) error

type NopTranslate

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

func (*NopTranslate) E

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

func (*NopTranslate) Lang

func (n *NopTranslate) Lang() string

func (*NopTranslate) T

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

type NopValidation

type NopValidation struct {
}

func (*NopValidation) Validate

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

type PanicError

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

func NewPanicError

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

func (*PanicError) AddTrace

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

func (*PanicError) Debug

func (p *PanicError) Debug() bool

func (*PanicError) Error

func (p *PanicError) Error() string

func (*PanicError) ExtractSnippets

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

func (*PanicError) HTML

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

func (*PanicError) JSONString

func (p *PanicError) JSONString() string

func (*PanicError) Parse

func (p *PanicError) Parse(stackSizes ...int) *PanicError

func (*PanicError) SetDebug

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

func (*PanicError) SetError

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

func (*PanicError) SetErrorString

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

func (*PanicError) String

func (p *PanicError) String() string

type Prefixer

type Prefixer interface {
	Prefix() string
}

type RawData

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

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

Assign 赋值

func (*RawData) Assignx

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

Assignx 批量赋值

func (*RawData) Error

func (d *RawData) Error() string

func (*RawData) GetCode

func (d *RawData) GetCode() State

func (*RawData) GetData

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

GetData 获取数据

func (*RawData) GetInfo

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

func (*RawData) GetURL

func (d *RawData) GetURL() string

func (*RawData) GetZone

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

func (*RawData) Gets

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

Gets 获取全部数据

func (*RawData) Reset

func (d *RawData) Reset() Data

func (*RawData) Set

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

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

func (*RawData) SetByMap

func (d *RawData) SetByMap(s Store) Data

SetByMap 批量设置属性

func (*RawData) SetCode

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

SetCode 设置状态码

func (*RawData) SetContext

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

SetContext 设置Context

func (*RawData) SetData

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

SetData 设置正常数据

func (*RawData) SetError

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

SetError 设置错误

func (*RawData) SetInfo

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

SetInfo 设置提示信息

func (*RawData) SetTmplFuncs

func (d *RawData) SetTmplFuncs()

SetTmplFuncs 设置模板函数

func (*RawData) SetURL

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

SetURL 设置跳转网址

func (*RawData) SetZone

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

SetZone 设置提示区域

func (*RawData) String

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 RendererRegister

type RendererRegister interface {
	SetRenderer(Renderer)
}

type Route

type Route struct {
	Host    string
	Method  string
	Path    string
	Handler Handler `json:"-" xml:"-"`
	Name    string
	Format  string
	Params  []string //param names
	Prefix  string
	Meta    H
	// contains filtered or unexported fields
}

func (*Route) IsZero

func (r *Route) IsZero() bool

func (*Route) SetName

func (r *Route) SetName(name string) IRouter

type RouteRegister

type RouteRegister interface {
	Group(prefix string, middleware ...interface{}) *Group
	Any(path string, h interface{}, middleware ...interface{}) IRouter
	Route(methods string, path string, h interface{}, middleware ...interface{}) IRouter
	Match(methods []string, path string, h interface{}, middleware ...interface{}) IRouter
	Connect(path string, h interface{}, m ...interface{}) IRouter
	Delete(path string, h interface{}, m ...interface{}) IRouter
	Get(path string, h interface{}, m ...interface{}) IRouter
	Head(path string, h interface{}, m ...interface{}) IRouter
	Options(path string, h interface{}, m ...interface{}) IRouter
	Patch(path string, h interface{}, m ...interface{}) IRouter
	Post(path string, h interface{}, m ...interface{}) IRouter
	Put(path string, h interface{}, m ...interface{}) IRouter
	Trace(path string, h interface{}, m ...interface{}) IRouter
	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 Routes

type Routes []*Route

func (Routes) SetName

func (r Routes) SetName(name string) IRouter

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

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

func (*SessionOptions) Clone

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

type Snippet struct {
	Number  int
	Code    string
	Current bool
}

type SnippetGroup

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

func (*SnippetGroup) String

func (sg *SnippetGroup) String() string

func (*SnippetGroup) TableRow

func (sg *SnippetGroup) TableRow() string

type State

type State int

State 状态码类型

func (State) HTTPCode

func (s State) HTTPCode() int

HTTPCode 返回HTTP状态码

func (State) Int

func (s State) Int() int

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

func (State) String

func (s State) String() string

type Status

type Status struct {
	Text string
	Code int
}

Status 状态值

type Store

type Store = param.Store

func Children

func Children(key interface{}, keys ...interface{}) Store

func GetStore

func GetStore(key interface{}, defaults ...interface{}) Store

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

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

type Transaction

type Transaction interface {
	Begin(ctx context.Context) error
	Rollback(ctx context.Context) error
	Commit(ctx context.Context) error
	End(ctx context.Context, succeed bool) error
}
var (
	DefaultNopTransaction   Transaction = &NopTransaction{}
	DefaultDebugTransaction Transaction = &DebugTransaction{}
)

type Translator

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

type URLBuilder

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

type ValidateResult

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

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

func NewValidateResult

func NewValidateResult() ValidateResult

type Validation

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

func (*Validation) Validate

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

func NewValidation() Validator

type ValidatorResult

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

func (*ValidatorResult) Error

func (v *ValidatorResult) Error() error

func (*ValidatorResult) Field

func (v *ValidatorResult) Field() string

func (*ValidatorResult) Ok

func (v *ValidatorResult) Ok() bool

func (*ValidatorResult) Raw

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

func (*ValidatorResult) SetError

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

func (*ValidatorResult) SetField

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

func (*ValidatorResult) SetRaw

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

Jump to

Keyboard shortcuts

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