echo

package module
v1.6.6 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: Apache-2.0 Imports: 44 Imported by: 945

README

Echo

Build Status Go 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.13

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)
e.Get("/user/<id:[\\d]+>", getUser)
Path Parameters
func getUser(c echo.Context) error {
	// User ID from path `users/:id`
	id := c.Param("id")
	// or id := c.Paramx("id").Uint64()
}
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")
	age := c.Queryx("age").Uint()
}
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")
	age := c.Formx("age").Uint()
}
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/v3/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 -

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
	MIMETextJavaScript                   = "text/javascript"
	MIMETextJavaScriptCharsetUTF8        = MIMETextJavaScript + "; " + CharsetUTF8
	MIMETextCSS                          = "text/css"
	MIMETextCSSCharsetUTF8               = MIMETextCSS + "; " + 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"
	HeaderXForwardedPort      = "X-Forwarded-Port"
	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"
	HeaderExpires             = "Expires"
	HeaderCacheControl        = "Cache-Control"
	CacheControlPrefix        = "public, max-age="
	HeaderConnection          = "Connection"
	HeaderTransferEncoding    = "Transfer-Encoding"

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

	// Content Type
	ContentTypeHTML  = "html"
	ContentTypeJSON  = "json"
	ContentTypeJSONP = "jsonp"
	ContentTypeXML   = "xml"
	ContentTypeText  = "text"

	// HTTP Scheme
	SchemeHTTP  = "http"
	SchemeHTTPS = "https"
)
View Source
const (
	SnippetLineNumbers = 13
	StackSize          = 4 << 10 // 4 KB
)

Variables

View Source
var (
	ErrBreak              = errors.New("[BREAK]")
	ErrContinue           = errors.New("[CONTINUE]")
	ErrExit               = errors.New("[EXIT]")
	ErrReturn             = errors.New("[RETURN]")
	ErrSliceIndexTooLarge = errors.New("the slice index value of the form field is too large")
)
View Source
var (
	//DefaultNopFilter 默认过滤器(map->struct)
	DefaultNopFilter FormDataFilter = func(k string, v []string) (string, []string) {
		return k, v
	}
	//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.ParseInLocation(layout, v[0], time.Local)
				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 (
	TimestampStringer  = param.TimestampStringer
	DateTimeStringer   = param.DateTimeStringer
	WhitespaceStringer = param.WhitespaceStringer
	Ignored            = param.Ignored
)
View Source
var (
	DefaultNopSession     Sessioner = &NopSession{}
	DefaultDebugSession   Sessioner = &DebugSession{}
	DefaultSession                  = DefaultNopSession
	DefaultSessionOptions           = NewSessionOptions(`cookie`, `SID`)
)
View Source
var (
	ErrUnsupportedMediaType         error = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrBadRequest                   error = NewHTTPError(http.StatusBadRequest)
	ErrPaymentRequired              error = NewHTTPError(http.StatusPaymentRequired)
	ErrNotAcceptable                error = NewHTTPError(http.StatusNotAcceptable)
	ErrProxyAuthRequired            error = NewHTTPError(http.StatusProxyAuthRequired)
	ErrRequestTimeout               error = NewHTTPError(http.StatusRequestTimeout)
	ErrConflict                     error = NewHTTPError(http.StatusConflict)
	ErrGone                         error = NewHTTPError(http.StatusGone)
	ErrLengthRequired               error = NewHTTPError(http.StatusLengthRequired)
	ErrPreconditionFailed           error = NewHTTPError(http.StatusPreconditionFailed)
	ErrRequestEntityTooLarge        error = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrRequestURITooLong            error = NewHTTPError(http.StatusRequestURITooLong)
	ErrRequestedRangeNotSatisfiable error = NewHTTPError(http.StatusRequestedRangeNotSatisfiable)
	ErrExpectationFailed            error = NewHTTPError(http.StatusExpectationFailed)
	ErrUnprocessableEntity          error = NewHTTPError(http.StatusUnprocessableEntity)
	ErrLocked                       error = NewHTTPError(http.StatusLocked)
	ErrFailedDependency             error = NewHTTPError(http.StatusFailedDependency)
	ErrTooEarly                     error = NewHTTPError(http.StatusTooEarly)
	ErrUpgradeRequired              error = NewHTTPError(http.StatusUpgradeRequired)
	ErrPreconditionRequired         error = NewHTTPError(http.StatusPreconditionRequired)
	ErrTooManyRequests              error = NewHTTPError(http.StatusTooManyRequests)
	ErrRequestHeaderFieldsTooLarge  error = NewHTTPError(http.StatusRequestHeaderFieldsTooLarge)
	ErrUnavailableForLegalReasons   error = NewHTTPError(http.StatusUnavailableForLegalReasons)
	ErrNotImplemented               error = NewHTTPError(http.StatusNotImplemented)
	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
	})

	ErrorHandler = func(err error) Handler {
		return HandlerFunc(func(c Context) error {
			return err
		})
	}

	MethodNotAllowedHandler = HandlerFunc(func(c Context) error {
		return ErrMethodNotAllowed
	})

	StringerMapStart = param.StringerMapStart
	StoreStart       = param.StoreStart
	HStart           = param.StoreStart
)
View Source
var (
	DefaultAcceptFormats = map[string]string{

		MIMEApplicationJSON:       ContentTypeJSON,
		`text/javascript`:         ContentTypeJSON,
		MIMEApplicationJavaScript: ContentTypeJSON,

		MIMEApplicationXML: ContentTypeXML,
		`text/xml`:         ContentTypeXML,

		MIMETextPlain: ContentTypeText,

		`*/*`:               ContentTypeHTML,
		`application/xhtml`: ContentTypeHTML,
		MIMETextHTML:        ContentTypeHTML,

		`*`: ContentTypeHTML,
	}
	DefaultFormatRenderers = map[string]FormatRender{
		ContentTypeJSON: func(c Context, data interface{}) error {
			return c.JSON(c.Data())
		},
		ContentTypeJSONP: func(c Context, data interface{}) error {
			return c.JSONP(c.Query(c.Echo().JSONPVarName), c.Data())
		},
		ContentTypeXML: func(c Context, data interface{}) error {
			return c.XML(c.Data())
		},
		ContentTypeText: func(c Context, data interface{}) error {
			return c.String(fmt.Sprint(data))
		},
	}
	DefaultBinderDecoders = map[string]func(interface{}, Context, BinderValueCustomDecoders, ...FormDataFilter) error{
		MIMEApplicationJSON: func(i interface{}, ctx Context, valueDecoders BinderValueCustomDecoders, filter ...FormDataFilter) error {
			body := ctx.Request().Body()
			if body == nil {
				return NewHTTPError(http.StatusBadRequest, "Request body can't be nil")
			}
			defer body.Close()
			err := json.NewDecoder(body).Decode(i)
			if err != nil {
				if ute, ok := err.(*stdJSON.UnmarshalTypeError); ok {
					return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset)).SetRaw(err)
				}
				if se, ok := err.(*stdJSON.SyntaxError); ok {
					return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error())).SetRaw(err)
				}
				return NewHTTPError(http.StatusBadRequest, err.Error()).SetRaw(err)
			}
			return err
		},
		MIMEApplicationXML: func(i interface{}, ctx Context, valueDecoders BinderValueCustomDecoders, filter ...FormDataFilter) error {
			body := ctx.Request().Body()
			if body == nil {
				return NewHTTPError(http.StatusBadRequest, "Request body can't be nil")
			}
			defer body.Close()
			err := xml.NewDecoder(body).Decode(i)
			if err != nil {
				if ute, ok := err.(*xml.UnsupportedTypeError); ok {
					return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported type error: type=%v, error=%v", ute.Type, ute.Error())).SetRaw(err)
				}
				if se, ok := err.(*xml.SyntaxError); ok {
					return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: line=%v, error=%v", se.Line, se.Error())).SetRaw(err)
				}
				return NewHTTPError(http.StatusBadRequest, err.Error()).SetRaw(err)
			}
			return err
		},
		MIMEApplicationForm: func(i interface{}, ctx Context, valueDecoders BinderValueCustomDecoders, filter ...FormDataFilter) error {
			return FormToStructWithDecoder(ctx.Echo(), i, ctx.Request().PostForm().All(), ``, valueDecoders, filter...)
		},
		MIMEMultipartForm: func(i interface{}, ctx Context, valueDecoders BinderValueCustomDecoders, filter ...FormDataFilter) error {
			_, err := ctx.Request().MultipartForm()
			if err != nil {
				return err
			}
			return FormToStructWithDecoder(ctx.Echo(), i, ctx.Request().Form().All(), ``, valueDecoders, filter...)
		},
		`*`: func(i interface{}, ctx Context, valueDecoders BinderValueCustomDecoders, filter ...FormDataFilter) error {
			return FormToStructWithDecoder(ctx.Echo(), i, ctx.Request().Form().All(), ``, valueDecoders, filter...)
		},
	}
	// DefaultHTMLFilter html filter (`form_filter:"html"`)
	DefaultHTMLFilter = func(v string) (r string) {
		return v
	}
	DefaultBinderValueEncoders = map[string]BinderValueEncoder{
		`joinKVRows`: binderValueEncoderJoinKVRows,
		`join`:       binderValueEncoderJoin,
		`unix2time`:  binderValueEncoderUnix2time,
	}
	DefaultBinderValueDecoders = map[string]BinderValueDecoder{
		`splitKVRows`: binderValueDecoderSplitKVRows,
		`split`:       binderValueDecoderSplit,
		`time2unix`:   binderValueDecoderTime2unix,
	}
)
View Source
var AsStore = param.AsStore
View Source
var (
	DefaultCookieOptions = &CookieOptions{
		Path: `/`,
	}
)
View Source
var DefaultNextURLVarName = `next`

Functions

func AddListener added in v1.6.0

func AddListener(listener events.Listener, names ...string) events.Emitterer

func AsStdContext added in v1.6.0

func AsStdContext(eCtx Context) context.Context

func Bool added in v1.4.3

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

func CSS added in v1.4.3

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

func CaptureTokens added in v1.3.5

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

func CaptureTokensByValues added in v1.6.0

func CaptureTokensByValues(values []string) *strings.Replacer

func Clear added in v1.6.0

func Clear(old []interface{}, clears ...interface{}) []interface{}

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

func CookieExpires(stdCookie *http.Cookie, expires time.Time)

CookieExpires 设置过期时间 所有浏览器都支持 如果仅仅设置Expires,因为过期时间是固定的,所以不会导致保存Cookie时被续期

func CookieMaxAge added in v1.6.0

func CookieMaxAge(stdCookie *http.Cookie, p int)

CookieMaxAge 设置有效时长(秒) IE6/7/8不支持 如果同时设置了MaxAge和Expires,则优先使用MaxAge 设置MaxAge则代表每次保存Cookie都会续期,因为MaxAge是基于保存时间来设置的

func CookieSameSite added in v1.6.0

func CookieSameSite(stdCookie *http.Cookie, p string)

CookieSameSite 设置SameSite

func CopyCookieOptions added in v1.6.0

func CopyCookieOptions(from *http.Cookie, to *http.Cookie)

CopyCookieOptions copy cookie options

func DateTime added in v1.4.3

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

func Decr added in v1.4.3

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

func DefaultRenderDataWrapper added in v1.6.0

func DefaultRenderDataWrapper(ctx Context, data interface{}) interface{}

func DefaultSkipper

func DefaultSkipper(c Context) bool

DefaultSkipper returns false which processes the middleware.

func Delete added in v1.4.2

func Delete(key interface{})

func DetectError added in v1.6.0

func DetectError(c Context, err error) error

func Dump added in v1.1.1

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

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

func E added in v1.4.3

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

func EventNames added in v1.6.0

func EventNames() []string

func Fire added in v1.6.0

func Fire(e interface{}) error

func FireByName added in v1.6.0

func FireByName(name string, options ...events.EventOption) error

func FireByNameWithMap added in v1.6.0

func FireByNameWithMap(name string, data events.Map) error

func FlatStructToForm added in v1.6.0

func FlatStructToForm(ctx Context, m interface{}, fieldNameFormatter FieldNameFormatter, formatters ...param.StringerMap)

FlatStructToForm 映射struct到form

func Float32 added in v1.4.3

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

func Float64 added in v1.4.3

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

func FormNames added in v1.1.0

func FormNames(s string) []string

FormNames user[name][test]

func FormToMap added in v1.6.0

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

func FormToMapWithDecoder added in v1.6.0

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

func FormToStruct added in v1.6.0

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

func FormToStructWithDecoder added in v1.6.0

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

func Get added in v1.4.2

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

func GetNextURL added in v1.6.0

func GetNextURL(ctx Context, varNames ...string) string

func GetOk added in v1.4.2

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

func GetOrSet added in v1.4.2

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

func GetOtherURL added in v1.6.0

func GetOtherURL(ctx Context, next string) string

func GetValidated added in v1.6.0

func GetValidated(c Context, defaults ...interface{}) interface{}

func HTML added in v1.4.3

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

func HTMLAttr added in v1.4.3

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

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

func Has(key interface{}) bool

func HasEvent added in v1.6.0

func HasEvent(name string) bool

func InErrorCode added in v1.6.0

func InErrorCode(err error, codes ...pkgCode.Code) bool

func InSliceFold added in v1.6.0

func InSliceFold(value string, items []string) bool

func Incr added in v1.4.3

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

func Int added in v1.4.3

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

func Int16 added in v1.4.3

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

func Int32 added in v1.4.3

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

func Int64 added in v1.4.3

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

func Int8 added in v1.4.3

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

func InterfacesToStrings added in v1.6.0

func InterfacesToStrings(args []interface{}) []string

func IsErrorCode added in v1.6.0

func IsErrorCode(err error, code pkgCode.Code) bool

func JS added in v1.4.3

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

func LogIf added in v1.6.0

func LogIf(err error, types ...string)

func Methods

func Methods() []string

Methods returns methods

func MustGetValidated added in v1.6.0

func MustGetValidated[T any](c Context) (T, error)

func MustValidated added in v1.6.0

func MustValidated[T any](c Context, v *T) error

func NamedStructMap

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

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

func NamedStructMapWithDecoder added in v1.6.0

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

func NewCookie

func NewCookie(key, value string, opt *CookieOptions) *http.Cookie

NewCookie 新建cookie对象

func NewEvent added in v1.6.0

func NewEvent(data interface{}, options ...events.EventOption) events.Event

func NewHost added in v1.6.0

func NewHost(name string) *host

func Off added in v1.6.0

func Off(name string) events.Emitterer

func On added in v1.6.0

func On(name string, handlers ...events.Listener) events.Emitterer

func OnCallback added in v1.6.0

func OnCallback(name string, cb func(events.Event) error, id ...string) events.Emitterer

func OnStream added in v1.6.0

func OnStream(name string, ch chan events.Event, id ...string) events.Emitterer

func PanicIf added in v1.6.0

func PanicIf(err error)

func ParseURIRegExp added in v1.6.0

func ParseURIRegExp(uriRegexp string, dflRegexp string) (names []string, format string, regExp *regexp.Regexp)

func Range added in v1.4.2

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

func RemoveListener added in v1.6.0

func RemoveListener(listener events.Listener) events.Emitterer

func ReturnToCurrentURL added in v1.6.0

func ReturnToCurrentURL(ctx Context, varNames ...string) string

func SafeGetFieldByName added in v1.6.0

func SafeGetFieldByName(value reflect.Value, name string) (v reflect.Value)

func Set added in v1.4.2

func Set(key, value interface{})

func SetAttachmentHeader added in v1.6.0

func SetAttachmentHeader(c Context, name string, setContentType bool, inline ...bool)

func SetFormValue added in v1.5.0

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

func SetFormValues added in v1.6.0

func SetFormValues(f engine.URLValuer, fName string, values []string)

func SetReflectValue added in v1.6.0

func SetReflectValue(source interface{}, dest reflect.Value) bool

func SetWorkDir added in v1.4.3

func SetWorkDir(dir string)

func Split added in v1.4.3

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

func String added in v1.4.3

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

func StructToForm added in v1.1.0

func StructToForm(ctx Context, m interface{}, topName string, fieldNameFormatter FieldNameFormatter, formatters ...param.StringerMap)

func T added in v1.3.9

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

T 标记为多语言文本

func Timestamp added in v1.4.3

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

func ToStdContext added in v1.6.0

func ToStdContext(ctx context.Context, eCtx Context) context.Context

func TranslateStringer added in v1.6.0

func TranslateStringer(t Translator, args ...interface{}) param.Stringer

func Trim added in v1.4.3

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

func URLDecode added in v1.6.0

func URLDecode(encoded string, rfc ...bool) (string, error)

func URLEncode added in v1.6.0

func URLEncode(s string, rfc ...bool) string

func Uint added in v1.4.3

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

func Uint16 added in v1.4.3

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

func Uint32 added in v1.4.3

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

func Uint64 added in v1.4.3

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

func Uint8 added in v1.4.3

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

func Validate added in v1.6.0

func Validate(c Context, item interface{}, args ...interface{}) error

func ValidateStruct added in v1.6.0

func ValidateStruct(c Context, item interface{}, args ...interface{}) error

func Wd added in v1.3.0

func Wd() string

func WithNextURL added in v1.6.0

func WithNextURL(ctx Context, urlStr string, varNames ...string) 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 AcceptQuality added in v1.6.0

type AcceptQuality struct {
	Quality float32 // maximum quality: 1
	Type    []*Accept
}

type Accepts added in v1.3.9

type Accepts struct {
	Raw     string
	Accepts []*AcceptQuality
}

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

type AfterValidate interface {
	AfterValidate(Context) error
}

type AsMiddleware added in v1.5.0

type AsMiddleware func(Context) error

func (AsMiddleware) Handle added in v1.5.0

func (m AsMiddleware) Handle(h Handler) Handler

type BaseRequestValidator added in v1.6.0

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

func NewBaseRequestValidator added in v1.6.0

func NewBaseRequestValidator(data interface{}, method ...string) *BaseRequestValidator

func (*BaseRequestValidator) Filters added in v1.6.0

func (*BaseRequestValidator) Methods added in v1.6.0

func (b *BaseRequestValidator) Methods() []string

func (*BaseRequestValidator) SetStruct added in v1.6.0

func (b *BaseRequestValidator) SetStruct(data interface{}) *BaseRequestValidator

func (*BaseRequestValidator) ValueDecoders added in v1.6.0

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(ctx context.Context) error

func (*BaseTransaction) Commit added in v1.3.9

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

func (*BaseTransaction) End added in v1.3.9

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

func (*BaseTransaction) Rollback added in v1.3.9

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

func (*BaseTransaction) Unwrap added in v1.6.0

func (b *BaseTransaction) Unwrap() Transaction

type BeforeBind added in v1.6.0

type BeforeBind interface {
	BeforeBind(Context) error
}

type BeforeValidate added in v1.6.0

type BeforeValidate interface {
	BeforeValidate(Context) error
}

type Binder

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

	BindWithDecoder(interface{}, Context, BinderValueCustomDecoders, ...FormDataFilter) error
	BindAndValidateWithDecoder(interface{}, Context, BinderValueCustomDecoders, ...FormDataFilter) error
	MustBindWithDecoder(interface{}, Context, BinderValueCustomDecoders, ...FormDataFilter) error
	MustBindAndValidateWithDecoder(interface{}, Context, BinderValueCustomDecoders, ...FormDataFilter) error
}

Binder is the interface that wraps the Bind method.

func NewBinder added in v1.3.0

func NewBinder(e *Echo) Binder

type BinderFormTopNamer added in v1.6.0

type BinderFormTopNamer interface {
	BinderFormTopName() string
}

type BinderKeyNormalizer added in v1.6.0

type BinderKeyNormalizer interface {
	BinderKeyNormalizer(string) string
}

type BinderValueCustomDecoder added in v1.6.0

type BinderValueCustomDecoder func(values []string) (interface{}, error)

type BinderValueCustomDecoders added in v1.6.0

type BinderValueCustomDecoders map[string]BinderValueCustomDecoder // 这里的 key 为结构体字段或map的key层级路径

type BinderValueCustomEncoder added in v1.6.0

type BinderValueCustomEncoder func(interface{}) []string

func FormStringer added in v1.6.0

func FormStringer(s param.Stringer) BinderValueCustomEncoder

type BinderValueCustomEncoders added in v1.6.0

type BinderValueCustomEncoders map[string]BinderValueCustomEncoder // 这里的 key 为表单字段层级路径

type BinderValueDecoder added in v1.6.0

type BinderValueDecoder func(field string, values []string, params string) (interface{}, error)

type BinderValueEncoder added in v1.6.0

type BinderValueEncoder func(field string, value interface{}, params string) []string

type Closer added in v1.2.0

type Closer interface {
	Close() error
}

type Context

type Context interface {
	context.Context
	events.Emitterer
	SetEmitterer(events.Emitterer)
	Handler() Handler

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

	//Standard Context
	StdContext() context.Context
	WithContext(ctx context.Context) *http.Request
	SetValue(key string, value interface{})

	SetValidator(Validator)
	Validator() Validator
	Validate(item interface{}, args ...interface{}) error
	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)
	Dispatch(route string) Handler

	Path() string
	P(int, ...string) string
	Param(string, ...string) string
	// ParamNames returns path parameter names.
	ParamNames() []string
	ParamValues() []string
	SetParamNames(names ...string)
	SetParamValues(values ...string)
	// Host
	HostParamNames() []string
	HostParamValues() []string
	HostParam(string, ...string) string
	HostP(int, ...string) string
	SetHostParamNames(names ...string)
	SetHostParamValues(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{}
	Incr(key string, n interface{}, defaults ...interface{}) int64
	Decr(key string, n interface{}, defaults ...interface{}) int64
	Delete(...string)
	Stored() Store
	Internal() *param.SafeMap

	Bind(interface{}, ...FormDataFilter) error
	BindAndValidate(interface{}, ...FormDataFilter) error
	MustBind(interface{}, ...FormDataFilter) error
	MustBindAndValidate(interface{}, ...FormDataFilter) error
	BindWithDecoder(interface{}, BinderValueCustomDecoders, ...FormDataFilter) error
	BindAndValidateWithDecoder(interface{}, BinderValueCustomDecoders, ...FormDataFilter) error
	MustBindWithDecoder(interface{}, BinderValueCustomDecoders, ...FormDataFilter) error
	MustBindAndValidateWithDecoder(interface{}, BinderValueCustomDecoders, ...FormDataFilter) error

	Render(string, interface{}, ...int) error
	RenderBy(string, func(string) ([]byte, error), interface{}, ...int) ([]byte, 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) error
	SSEvent(string, chan interface{}) error
	File(string, ...http.FileSystem) error
	CacheableFile(string, time.Duration, ...http.FileSystem) error
	Attachment(io.Reader, string, time.Time, ...bool) error
	CacheableAttachment(io.Reader, string, time.Time, time.Duration, ...bool) error
	NotModified() error
	NoContent(...int) error
	Redirect(string, ...int) error
	Error(err error)
	NewError(code pkgCode.Code, msg string, args ...interface{}) *Error
	NewErrorWith(err error, code pkgCode.Code, args ...interface{}) *Error
	SetCode(int)
	Code() int
	SetData(Data)
	Data() Data

	IsValidCache(modifiedAt time.Time) bool
	SetCacheHeader(modifiedAt time.Time, maxAge ...time.Duration)

	// 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.Reader, string, time.Time, ...time.Duration) error
	ServeCallbackContent(func(Context) (io.Reader, error), string, time.Time, ...time.Duration) 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)
	SetRenderDataWrapper(DataWrapper)
	Renderer() Renderer
	RenderDataWrapper() DataWrapper

	SetCookieOptions(*CookieOptions)
	CookieOptions() *CookieOptions
	NewCookie(string, string) *http.Cookie
	Cookie() Cookier
	GetCookie(string) string
	// SetCookie @param:key,value,maxAge(seconds),path(/),domain,secure,httpOnly,sameSite(lax/strict/default)
	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)
	SetDefaultExtension(string)
	DefaultExtension() string
	ResolveFormat() string
	Accept() *Accepts
	Protocol() string
	Site() string
	RequestURI() 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 ...func(*multipart.FileHeader) (string, error)) (*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
	OnHostFound(func(Context) (bool, error)) Context
	FireHostFound() (bool, error)
}

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

func FromStdContext added in v1.6.0

func FromStdContext(c context.Context) (Context, bool)

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

	// Expires
	Expires time.Time

	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

func (*CookieOptions) SetMaxAge added in v1.6.0

func (c *CookieOptions) SetMaxAge(maxAge int) *CookieOptions

type Cookier

type Cookier interface {
	Get(key string) string
	Add(cookies ...*http.Cookie) Cookier
	Set(key string, val string, args ...interface{}) Cookier
	Send()
}

Cookier interface

func NewCookier

func NewCookier(ctx Context) Cookier

NewCookier create a cookie instance

type Data

type Data 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 pkgCode.Code, info interface{}, zone interface{}, data interface{})
	GetCode() pkgCode.Code
	GetInfo() interface{}
	GetZone() interface{}
	GetData() interface{}
	GetURL() string
	JSONP(callback string, codes ...int) error
	JSON(codes ...int) error
	XML(codes ...int) error
}

Data 响应数据

type DataWrapper added in v1.6.0

type DataWrapper func(Context, interface{}) interface{}

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) AddPreSaveHook added in v1.6.0

func (n *DebugSession) AddPreSaveHook(_ func(Context) error)

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) MustID added in v1.6.0

func (n *DebugSession) MustID() string

func (*DebugSession) Options added in v1.3.5

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

func (*DebugSession) RemoveID added in v1.6.0

func (n *DebugSession) RemoveID(sessionID string) error

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, notReload ...bool) error

func (*DebugSession) SetPreSaveHook added in v1.6.0

func (n *DebugSession) SetPreSaveHook(_ ...func(Context) error)

type DebugTransaction added in v1.5.0

type DebugTransaction struct {
}

func (*DebugTransaction) Begin added in v1.5.0

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

func (*DebugTransaction) Commit added in v1.5.0

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

func (*DebugTransaction) End added in v1.5.0

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

func (*DebugTransaction) Rollback added in v1.5.0

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

type Echo

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

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

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

func (*Echo) AddBinderValueDecoder added in v1.6.0

func (e *Echo) AddBinderValueDecoder(name string, decoder BinderValueDecoder) *Echo

func (*Echo) AddBinderValueEncoder added in v1.6.0

func (e *Echo) AddBinderValueEncoder(name string, encoder BinderValueEncoder) *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{}) 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) AutoDetectRenderFormat added in v1.6.0

func (e *Echo) AutoDetectRenderFormat(c Context, data interface{}) (bool, error)

func (*Echo) Binder

func (e *Echo) Binder() Binder

Binder returns the binder instance.

func (*Echo) CallBinderValueDecoder added in v1.6.0

func (e *Echo) CallBinderValueDecoder(name string, field string, values []string, params string) (interface{}, error)

func (*Echo) CallBinderValueEncoder added in v1.6.0

func (e *Echo) CallBinderValueEncoder(name string, field string, value interface{}, params string) ([]string, error)

func (*Echo) Clear added in v1.3.0

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

Clear middleware

func (*Echo) ClearPre added in v1.6.0

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

ClearPre Clear premiddleware

func (*Echo) Commit added in v1.6.0

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) DefaultExtension added in v1.6.0

func (e *Echo) DefaultExtension() string

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

Head adds a HEAD route > handler to the router.

func (*Echo) Host added in v1.6.0

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

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) MaxRequestBodySize added in v1.6.0

func (e *Echo) MaxRequestBodySize() int

func (*Echo) MetaHandler

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

MetaHandler Add meta information about endpoint

func (*Echo) MetaHandlerWithRequest added in v1.6.0

func (e *Echo) MetaHandlerWithRequest(m H, handler interface{}, request interface{}, methods ...string) Handler

MetaHandlerWithRequest Add meta information about endpoint

func (*Echo) NamedRoutes

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

NamedRoutes returns the registered handler name.

func (*Echo) NewContext added in v1.5.0

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

func (*Echo) OnHostFound added in v1.6.0

func (e *Echo) OnHostFound(onHostFound func(Context) (bool, error)) *Echo

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 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{}) 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 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) RealIPConfig added in v1.6.0

func (e *Echo) RealIPConfig() *realip.Config

func (*Echo) RebuildRouter

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

RebuildRouter rebuild router

func (*Echo) RemoveFormatRenderer added in v1.3.7

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

func (*Echo) RenderDataWrapper added in v1.6.0

func (e *Echo) RenderDataWrapper() DataWrapper

RenderDataWrapper .

func (*Echo) Renderer added in v1.3.0

func (e *Echo) Renderer() Renderer

Renderer returns the renderer instance.

func (*Echo) Reset added in v1.6.0

func (e *Echo) Reset() *Echo

func (*Echo) Rewriter added in v1.6.0

func (e *Echo) Rewriter() Rewriter

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 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) SetDefaultExtension added in v1.6.0

func (e *Echo) SetDefaultExtension(ext string)

func (*Echo) SetFormSliceMaxIndex added in v1.6.0

func (e *Echo) SetFormSliceMaxIndex(max int) *Echo

func (*Echo) SetFormatRenderers added in v1.3.7

func (e *Echo) SetFormatRenderers(formatRenderers map[string]FormatRender) *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) SetMaxRequestBodySize added in v1.6.0

func (e *Echo) SetMaxRequestBodySize(maxRequestBodySize int) *Echo

func (*Echo) SetMiddlewareWrapper added in v1.1.0

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

func (*Echo) SetPrefix added in v1.4.3

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

func (*Echo) SetRenderDataWrapper added in v1.6.0

func (e *Echo) SetRenderDataWrapper(dataWrapper DataWrapper)

SetRenderDataWrapper .

func (*Echo) SetRenderer

func (e *Echo) SetRenderer(r Renderer)

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

func (*Echo) SetRewriter added in v1.6.0

func (e *Echo) SetRewriter(r Rewriter)

func (*Echo) SetValidator added in v1.6.0

func (e *Echo) SetValidator(validator Validator) *Echo

func (*Echo) Shutdown added in v1.6.0

func (e *Echo) Shutdown(ctx context.Context) error

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

Trace adds a TRACE route > handler to the router.

func (*Echo) TypeHost added in v1.6.0

func (e *Echo) TypeHost(alias string, args ...interface{}) (r TypeHost)

TypeHost TypeHost(`blog`).URI(`login`)

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

type ErrUnwrap interface {
	Unwrap() error
}

type Error added in v1.6.0

type Error struct {
	Code    pkgCode.Code
	Message string
	Zone    string
	Extra   H
	// contains filtered or unexported fields
}

func AsError added in v1.6.0

func AsError(code pkgCode.Code) *Error

func NewError added in v1.6.0

func NewError(msg string, code ...pkgCode.Code) *Error

func NewErrorWith added in v1.6.0

func NewErrorWith(err error, msg string, code ...pkgCode.Code) *Error

func (*Error) Cause added in v1.6.0

func (e *Error) Cause() error

func (*Error) Clone added in v1.6.0

func (e *Error) Clone() *Error

func (*Error) Delete added in v1.6.0

func (e *Error) Delete(keys ...string) *Error

func (*Error) Error added in v1.6.0

func (e *Error) Error() string

Error returns message.

func (*Error) ErrorCode added in v1.6.0

func (e *Error) ErrorCode() int

func (*Error) NoClone added in v1.6.0

func (e *Error) NoClone() *Error

func (*Error) Set added in v1.6.0

func (e *Error) Set(key string, value interface{}) *Error

func (*Error) SetError added in v1.6.0

func (e *Error) SetError(err error) *Error

func (*Error) SetMessage added in v1.6.0

func (e *Error) SetMessage(message string) *Error

func (*Error) SetZone added in v1.6.0

func (e *Error) SetZone(zone string) *Error

func (*Error) Unwrap added in v1.6.0

func (e *Error) Unwrap() error

type Event added in v1.6.0

type Event = events.Event

type FieldNameFormatter added in v1.1.0

type FieldNameFormatter func(topName, fieldName string) string

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

var (
	//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
	}
	//ArrayFieldNameFormatter 格式化函数(struct->form)
	ArrayFieldNameFormatter 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
	}
)

func MakeArrayFieldNameFormatter added in v1.6.0

func MakeArrayFieldNameFormatter(keyFormatter func(string) string) FieldNameFormatter

type FiltersGetter added in v1.6.0

type FiltersGetter interface {
	Filters(Context) []FormDataFilter
}

type FormDataFilter added in v1.1.0

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

FormDataFilter 将map映射到结构体时,对名称和值的过滤处理,如果返回的名称为空,则跳过本字段 这里的 key 为结构体字段或map的key层级路径,如果有父级则用星号“*”表示,例如:*.Name

func ExcludeFieldName added in v1.5.0

func ExcludeFieldName(fieldNames ...string) FormDataFilter

ExcludeFieldName 排除字段

func FormatFieldValue added in v1.5.0

func FormatFieldValue(formatters map[string]FormDataFilter, keyNormalizerArg ...func(string) string) FormDataFilter

FormatFieldValue 格式化字段值

func IncludeFieldName added in v1.5.0

func IncludeFieldName(fieldNames ...string) FormDataFilter

IncludeFieldName 包含字段

type FormNameFormatterGetter added in v1.6.0

type FormNameFormatterGetter interface {
	FormNameFormatter(Context) FieldNameFormatter
}

type FormatRender added in v1.6.0

type FormatRender func(ctx Context, data interface{}) error

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

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

func (*Group) Alias added in v1.6.0

func (g *Group) Alias(alias string) Hoster

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

func (g *Group) MetaHandler(m H, handler interface{}, requests ...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 adds handler to the middleware chain.

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) SetAlias added in v1.6.0

func (g *Group) SetAlias(alias string) *Group

func (*Group) SetMeta added in v1.6.0

func (g *Group) SetMeta(meta H) *Group

func (*Group) SetMetaKV added in v1.6.0

func (g *Group) SetMetaKV(key string, value interface{}) *Group

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

func GetStoreByKeys added in v1.6.0

func GetStoreByKeys(key interface{}, keys ...string) H

type HTTPError

type HTTPError struct {
	Code    int
	Message string
	// contains filtered or unexported fields
}

func NewHTTPError

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

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns message.

func (*HTTPError) Raw added in v1.6.0

func (e *HTTPError) Raw() error

Raw gets the raw error

func (*HTTPError) SetRaw added in v1.6.0

func (e *HTTPError) SetRaw(err error) *HTTPError

SetRaw sets the raw error

func (*HTTPError) Unwrap added in v1.6.0

func (e *HTTPError) Unwrap() error

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

type HandlerFuncs map[string]func(Context) error

func (HandlerFuncs) Call added in v1.6.0

func (h HandlerFuncs) Call(c Context, key string) error

func (*HandlerFuncs) Register added in v1.6.0

func (h *HandlerFuncs) Register(key string, fn func(Context) error)

func (*HandlerFuncs) Unregister added in v1.6.0

func (h *HandlerFuncs) Unregister(keys ...string)

type Host added in v1.6.0

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

func (*Host) Host added in v1.6.0

func (h *Host) Host(args ...interface{}) (r TypeHost)

type Hoster added in v1.6.0

type Hoster interface {
	Name() string
	Alias() string
	Format(args ...interface{}) string
	FormatMap(params H) string
	RegExp() *regexp.Regexp
	Match(host string) (r []string, hasExpr bool)
}

type ICore added in v1.1.0

type IRouter added in v1.6.0

type IRouter interface {
	SetName(string) IRouter
	GetName() string
	SetMeta(param.Store) IRouter
	SetMetaKV(string, interface{}) IRouter
	GetMeta() param.Store
}

type KV added in v1.1.1

type KV struct {
	K string
	V string
	H H           `json:",omitempty" xml:",omitempty"`
	X interface{} `json:",omitempty" xml:",omitempty"`
	// contains filtered or unexported fields
}

KV 键值对

func NewKV added in v1.6.0

func NewKV(k, v string) *KV

func (*KV) Fn added in v1.6.0

func (a *KV) Fn() func(context.Context) interface{}

func (*KV) SetFn added in v1.6.0

func (a *KV) SetFn(fn func(context.Context) interface{}) *KV

func (*KV) SetH added in v1.6.0

func (a *KV) SetH(h H) *KV

func (*KV) SetHKV added in v1.6.0

func (a *KV) SetHKV(k string, v interface{}) *KV

func (*KV) SetK added in v1.6.0

func (a *KV) SetK(k string) *KV

func (*KV) SetKV added in v1.6.0

func (a *KV) SetKV(k, v string) *KV

func (*KV) SetV added in v1.6.0

func (a *KV) SetV(v string) *KV

func (*KV) SetX added in v1.6.0

func (a *KV) SetX(x interface{}) *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, options ...KVOption) *KVData

Add 添加键值

func (*KVData) AddItem added in v1.6.0

func (a *KVData) AddItem(item *KV) *KVData

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, defaults ...string) string

func (*KVData) GetItem added in v1.6.0

func (a *KVData) GetItem(k string, defaults ...func() *KV) *KV

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) Keys added in v1.6.0

func (a *KVData) Keys() []string

Keys 返回所有K值

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, options ...KVOption) *KVData

Set 设置首个键值

func (*KVData) SetItem added in v1.6.0

func (a *KVData) SetItem(item *KV) *KVData

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, options ...KVOption)

func (*KVList) AddItem added in v1.6.0

func (list *KVList) AddItem(item *KV)

func (*KVList) Delete added in v1.6.0

func (list *KVList) Delete(i int)

func (*KVList) Reset added in v1.3.5

func (list *KVList) Reset()

type KVOption added in v1.6.0

type KVOption func(*KV)

func KVOptFn added in v1.6.0

func KVOptFn(fn func(context.Context) interface{}) KVOption

func KVOptH added in v1.6.0

func KVOptH(h H) KVOption

func KVOptHKV added in v1.6.0

func KVOptHKV(k string, v interface{}) KVOption

func KVOptK added in v1.6.0

func KVOptK(k string) KVOption

func KVOptV added in v1.6.0

func KVOptV(v string) KVOption

func KVOptX added in v1.6.0

func KVOptX(x interface{}) KVOption

type LangCode added in v1.6.0

type LangCode interface {
	String() string    // all lowercase characters
	Normalize() string // lowercase(language)-uppercase(region)
	Format(regionUppercase bool, separator ...string) string
	Language() string
	Region(regionUppercase bool) string
}

func NewLangCode added in v1.6.0

func NewLangCode(language string, separator ...string) LangCode

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) Handle added in v1.6.0

func (m *MetaHandler) Handle(c Context) error

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

type MetaValidator interface {
	MethodGetter
	FiltersGetter
	ValueDecodersGetter
}

type MethodGetter added in v1.6.0

type MethodGetter interface {
	Methods() []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) AddPreSaveHook added in v1.6.0

func (n *NopSession) AddPreSaveHook(_ func(Context) error)

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) MustID added in v1.6.0

func (n *NopSession) MustID() string

func (*NopSession) Options

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

func (*NopSession) RemoveID added in v1.6.0

func (n *NopSession) RemoveID(sessionID string) error

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, notReload ...bool) error

func (*NopSession) SetPreSaveHook added in v1.6.0

func (n *NopSession) SetPreSaveHook(_ ...func(Context) error)

type NopTranslate

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

func (*NopTranslate) E added in v1.4.3

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

func (*NopTranslate) Lang

func (n *NopTranslate) Lang() LangCode

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{}, _ ...interface{}) 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, debugAndDisableStackAll ...bool) *PanicError

func ParseTemplateError added in v1.6.0

func ParseTemplateError(err error, sourceContent string) *PanicError

func (*PanicError) AddTrace added in v1.3.0

func (p *PanicError) AddTrace(trace *Trace, content ...string) *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) ExtractFileSnippets added in v1.6.0

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

func (*PanicError) ExtractSnippets added in v1.3.0

func (p *PanicError) ExtractSnippets(content string, 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) Parse added in v1.4.3

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

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  pkgCode.Code
	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) Error added in v1.3.0

func (d *RawData) Error() string

func (*RawData) GetCode added in v1.3.0

func (d *RawData) GetCode() pkgCode.Code

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) GetURL added in v1.5.0

func (d *RawData) GetURL() string

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() (pkgCode.Code, interface{}, interface{}, interface{})

Gets 获取全部数据

func (*RawData) JSON added in v1.6.0

func (d *RawData) JSON(codes ...int) error

func (*RawData) JSONP added in v1.6.0

func (d *RawData) JSONP(callback string, codes ...int) error

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) SetByMap added in v1.5.0

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

SetByMap 批量设置属性

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

func (*RawData) XML added in v1.6.0

func (d *RawData) XML(codes ...int) error

type RenderData added in v1.6.0

type RenderData struct {
	Func   template.FuncMap
	Data   interface{}
	Stored param.MapReadonly
	// contains filtered or unexported fields
}

func NewRenderData added in v1.6.0

func NewRenderData(ctx Context, data interface{}) *RenderData

func (*RenderData) CaptchaForm added in v1.6.0

func (r *RenderData) CaptchaForm(args ...interface{}) template.HTML

func (*RenderData) Cookie added in v1.6.0

func (r *RenderData) Cookie() Cookier

func (*RenderData) Decr added in v1.6.0

func (r *RenderData) Decr(key string, n interface{}, defaults ...interface{}) int64

func (*RenderData) Domain added in v1.6.0

func (r *RenderData) Domain() string

func (*RenderData) DurationFormat added in v1.6.0

func (r *RenderData) DurationFormat(t interface{}, args ...string) *com.Durafmt

func (*RenderData) Ext added in v1.6.0

func (r *RenderData) Ext() string

func (*RenderData) Fetch added in v1.6.0

func (r *RenderData) Fetch(tmpl string, data interface{}) template.HTML

func (*RenderData) Flash added in v1.6.0

func (r *RenderData) Flash(keys ...string) interface{}

func (*RenderData) Form added in v1.6.0

func (r *RenderData) Form(key string, defaults ...string) string

func (*RenderData) FormValues added in v1.6.0

func (r *RenderData) FormValues(key string) []string

func (*RenderData) Formx added in v1.6.0

func (r *RenderData) Formx(key string, defaults ...string) param.String

func (*RenderData) FormxValues added in v1.6.0

func (r *RenderData) FormxValues(key string) param.StringSlice

func (*RenderData) Get added in v1.6.0

func (r *RenderData) Get(key string, defaults ...interface{}) interface{}

func (*RenderData) GetNextURL added in v1.6.0

func (r *RenderData) GetNextURL(varNames ...string) string

func (*RenderData) GetOtherURL added in v1.6.0

func (r *RenderData) GetOtherURL(urlStr string, next string) string

func (*RenderData) HasAnyRequest added in v1.6.0

func (r *RenderData) HasAnyRequest() bool

func (*RenderData) Header added in v1.6.0

func (r *RenderData) Header() engine.Header

func (*RenderData) Incr added in v1.6.0

func (r *RenderData) Incr(key string, n interface{}, defaults ...interface{}) int64

func (*RenderData) Lang added in v1.6.0

func (r *RenderData) Lang() LangCode

func (*RenderData) MakeURL added in v1.6.0

func (r *RenderData) MakeURL(h interface{}, args ...interface{}) string

func (*RenderData) Now added in v1.6.0

func (r *RenderData) Now() *com.Time

func (*RenderData) Param added in v1.6.0

func (r *RenderData) Param(key string, defaults ...string) string

func (*RenderData) Paramx added in v1.6.0

func (r *RenderData) Paramx(key string, defaults ...string) param.String

func (*RenderData) Path added in v1.6.0

func (r *RenderData) Path() string

func (*RenderData) Port added in v1.6.0

func (r *RenderData) Port() int

func (*RenderData) Prefix added in v1.6.0

func (r *RenderData) Prefix() string

func (*RenderData) Queries added in v1.6.0

func (r *RenderData) Queries() map[string][]string

func (*RenderData) Query added in v1.6.0

func (r *RenderData) Query(key string, defaults ...string) string

func (*RenderData) QueryValues added in v1.6.0

func (r *RenderData) QueryValues(key string) []string

func (*RenderData) Queryx added in v1.6.0

func (r *RenderData) Queryx(key string, defaults ...string) param.String

func (*RenderData) QueryxValues added in v1.6.0

func (r *RenderData) QueryxValues(key string) param.StringSlice

func (*RenderData) Referer added in v1.6.0

func (r *RenderData) Referer() string

func (*RenderData) RequestURI added in v1.6.0

func (r *RenderData) RequestURI() string

func (*RenderData) ReturnToCurrentURL added in v1.6.0

func (r *RenderData) ReturnToCurrentURL(varNames ...string) string

func (*RenderData) Scheme added in v1.6.0

func (r *RenderData) Scheme() string

func (*RenderData) Session added in v1.6.0

func (r *RenderData) Session() Sessioner

func (*RenderData) Set added in v1.6.0

func (r *RenderData) Set(key string, value interface{}) string

func (*RenderData) Site added in v1.6.0

func (r *RenderData) Site() string

func (*RenderData) SiteURI added in v1.6.0

func (r *RenderData) SiteURI() string

func (*RenderData) T added in v1.6.0

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

func (*RenderData) ThemeColor added in v1.6.0

func (r *RenderData) ThemeColor() string

func (*RenderData) TimeAgo added in v1.6.0

func (r *RenderData) TimeAgo(v interface{}, options ...string) string

func (*RenderData) TsHumanize added in v1.6.0

func (r *RenderData) TsHumanize(startTime interface{}, endTime ...interface{}) string

func (*RenderData) URI added in v1.6.0

func (r *RenderData) URI() string

func (*RenderData) URL added in v1.6.0

func (r *RenderData) URL() engine.URL

func (*RenderData) UnixTime added in v1.6.0

func (r *RenderData) UnixTime() int64

func (*RenderData) WithNextURL added in v1.6.0

func (r *RenderData) WithNextURL(urlStr string, varNames ...string) string

type Renderer

type Renderer interface {
	Render(w io.Writer, name string, data interface{}, c Context) error
	RenderBy(w io.Writer, name string, content func(string) ([]byte, error), data interface{}, c Context) error
}

Renderer is the interface that wraps the Render method.

type RendererRegister added in v1.4.3

type RendererRegister interface {
	SetRenderer(Renderer)
}

type RequestValidator added in v1.6.0

type RequestValidator func() MetaValidator

type Rewriter added in v1.6.0

type Rewriter interface {
	Rewrite(string) string
}

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) Bool added in v1.6.0

func (r *Route) Bool(name string, defaults ...interface{}) bool

func (*Route) Float32 added in v1.6.0

func (r *Route) Float32(name string, defaults ...interface{}) float32

func (*Route) Float64 added in v1.6.0

func (r *Route) Float64(name string, defaults ...interface{}) float64

func (*Route) Get added in v1.6.0

func (r *Route) Get(name string, defaults ...interface{}) interface{}

func (*Route) GetMeta added in v1.6.0

func (r *Route) GetMeta() H

func (*Route) GetName added in v1.6.0

func (r *Route) GetName() string

func (*Route) GetStore added in v1.6.0

func (r *Route) GetStore(names ...string) H

func (*Route) Int added in v1.6.0

func (r *Route) Int(name string, defaults ...interface{}) int

func (*Route) Int32 added in v1.6.0

func (r *Route) Int32(name string, defaults ...interface{}) int32

func (*Route) Int64 added in v1.6.0

func (r *Route) Int64(name string, defaults ...interface{}) int64

func (*Route) IsZero added in v1.3.0

func (r *Route) IsZero() bool

func (*Route) MakeURI added in v1.6.0

func (r *Route) MakeURI(e *Echo, params ...interface{}) (uri string)

func (*Route) SetMeta added in v1.6.0

func (r *Route) SetMeta(meta H) IRouter

func (*Route) SetMetaKV added in v1.6.0

func (r *Route) SetMetaKV(key string, value interface{}) IRouter

func (*Route) SetName added in v1.6.0

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

func (*Route) String added in v1.6.0

func (r *Route) String(name string, defaults ...interface{}) string

func (*Route) Uint added in v1.6.0

func (r *Route) Uint(name string, defaults ...interface{}) uint

func (*Route) Uint32 added in v1.6.0

func (r *Route) Uint32(name string, defaults ...interface{}) uint32

func (*Route) Uint64 added in v1.6.0

func (r *Route) Uint64(name string, defaults ...interface{}) uint64

type RouteRegister added in v1.1.0

type RouteRegister interface {
	MiddlewareRegister
	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)
	Prefix() 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) Dispatch added in v1.6.0

func (r *Router) Dispatch(c Context, path string, _method ...string) Handler

func (*Router) Find

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

func (*Router) Handle

func (r *Router) Handle(c Context) Handler

func (*Router) String added in v1.6.0

func (r *Router) String() string

func (*Router) Tree added in v1.6.0

func (r *Router) Tree() H

type Routes added in v1.6.0

type Routes []*Route

func (Routes) GetMeta added in v1.6.0

func (r Routes) GetMeta() H

func (Routes) GetName added in v1.6.0

func (r Routes) GetName() string

func (Routes) SetMeta added in v1.6.0

func (r Routes) SetMeta(meta H) IRouter

func (Routes) SetMetaKV added in v1.6.0

func (r Routes) SetMetaKV(key string, value interface{}) IRouter

func (Routes) SetName added in v1.6.0

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 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, notReload ...bool) error
	ID() string
	MustID() string
	RemoveID(sessionID string) error
	// 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
	AddPreSaveHook(func(Context) error)
	SetPreSaveHook(...func(Context) 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 Store added in v1.3.7

type Store = param.Store

func Children added in v1.4.3

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

func GetStore added in v1.4.3

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 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(ctx context.Context) error
	Rollback(ctx context.Context) error
	Commit(ctx context.Context) error
	End(ctx context.Context, succeed bool) error
}
var (
	DefaultNopTransaction               = NewTransaction(nil)
	DefaultDebugTransaction Transaction = &DebugTransaction{}
)

type Translator

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

type TypeHost added in v1.6.0

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

func (TypeHost) String added in v1.6.0

func (t TypeHost) String() string

func (TypeHost) URI added in v1.6.0

func (t TypeHost) URI(handler interface{}, params ...interface{}) string

type URLBuilder added in v1.1.0

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

type UnwrapTransaction added in v1.6.0

type UnwrapTransaction interface {
	Unwrap() Transaction
}

type ValidateResult added in v1.3.0

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

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

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

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

type Validator

type Validator interface {
	Validate(i interface{}, args ...interface{}) 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) AsError added in v1.6.0

func (v *ValidatorResult) AsError() 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

func (*ValidatorResult) Unwrap added in v1.6.0

func (v *ValidatorResult) Unwrap() error

type ValueDecodersGetter added in v1.6.0

type ValueDecodersGetter interface {
	ValueDecoders(Context) BinderValueCustomDecoders
}

type ValueEncodersGetter added in v1.6.0

type ValueEncodersGetter interface {
	ValueEncoders(Context) BinderValueCustomEncoders
}

type ValueStringersGetter added in v1.6.0

type ValueStringersGetter interface {
	ValueStringers(Context) param.StringerMap
}

Jump to

Keyboard shortcuts

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