Documentation
¶
Overview ¶
Package lessgo implements a simple, stable, efficient and flexible web framework for Go.
Author1: https://github.com/henrylee2cn Author2: https://github.com/changyu72
Index ¶
- Constants
- Variables
- func AfterUse(middleware ...MiddlewareConfig)
- func BeforeUse(middleware ...MiddlewareConfig)
- func ContentTypeByExtension(name string) (t string)
- func DefaultDB() *xorm.Engine
- func DisableServer()
- func EnableServer()
- func GetDB(name string) (*xorm.Engine, bool)
- func GetHome() string
- func Lessgo() *lessgo
- func LoadAppConfig() (err error)
- func LoadDBConfig() (err error)
- func Logger() logs.Logger
- func PreUse(middleware ...MiddlewareConfig)
- func ReregisterRouter()
- func Root(nodes ...*VirtRouter)
- func Run()
- func ServerEnable() bool
- func Sessions() *session.Manager
- func SetHome(homeurl string)
- func SimpleToken6238(secret string, length uint8, isBase32Secret bool, period uint8) *token.TOTP
- func SufUse(middleware ...MiddlewareConfig)
- func Token4226(secret string, length uint8, counter uint64, isBase32Secret bool) *token.HOTP
- func Token6238(secret string, length uint8, isBase32Secret bool, period uint8, ...) *token.TOTP
- type ApiHandler
- type ApiMiddleware
- type Binder
- type Cachefile
- type CommMsg
- type ConfMiddlewareFunc
- type Config
- type Context
- type DBConfig
- type Echo
- func (e *Echo) AddLogAdapter(adaptername string, config string) error
- func (e *Echo) AfterUse(middleware ...MiddlewareFunc)
- func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (e *Echo) BeforeUse(middleware ...MiddlewareFunc)
- func (e *Echo) CaseSensitive() bool
- func (e *Echo) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) Debug() bool
- func (e *Echo) DefaultHTTPErrorHandler(err error, c Context)
- func (e *Echo) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) File(path, file string, middleware ...MiddlewareFunc)
- func (e *Echo) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) GetContext() Context
- func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group)
- func (e *Echo) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) LogFuncCallDepth(b bool)
- func (e *Echo) Logger() logs.Logger
- func (e *Echo) Match(methods []string, path string, handler HandlerFunc, ...)
- func (e *Echo) MemoryCacheEnable() bool
- func (e *Echo) NewContext(resp *Response, req *Request) Context
- func (e *Echo) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) PreUse(middleware ...MiddlewareFunc)
- func (e *Echo) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) PutContext(c Context)
- func (e *Echo) Router() *Router
- func (e *Echo) Routes() []Route
- func (e *Echo) Run(address, tlsCertfile, tlsKeyfile string, ...)
- func (e *Echo) ServeHTTP(rw http.ResponseWriter, req *http.Request)
- func (e *Echo) Sessions() *session.Manager
- func (e *Echo) SetBinder(b Binder)
- func (e *Echo) SetCaseSensitive(sensitive bool)
- func (e *Echo) SetDebug(on bool)
- func (e *Echo) SetHTTPErrorHandler(h HTTPErrorHandler)
- func (e *Echo) SetLogLevel(l int)
- func (e *Echo) SetMemoryCache(m *MemoryCache)
- func (e *Echo) SetRenderer(r Renderer)
- func (e *Echo) SetSessions(sessions *session.Manager)
- func (e *Echo) Static(prefix, root string, middleware ...MiddlewareFunc)
- func (e *Echo) SufUse(middleware ...MiddlewareFunc)
- func (e *Echo) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string
- func (e *Echo) URL(h HandlerFunc, params ...interface{}) string
- func (e *Echo) WebSocket(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- type FileCacheConfig
- type Group
- func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *Group) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Group(prefix string, m ...MiddlewareFunc) *Group
- func (g *Group) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Match(methods []string, path string, handler HandlerFunc, ...)
- func (g *Group) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Use(m ...MiddlewareFunc)
- type HTTPError
- type HTTPErrorHandler
- type HandlerFunc
- type Info
- type Listen
- type LogConfig
- type MemoryCache
- type Middleware
- type MiddlewareConfig
- type MiddlewareFunc
- type Param
- type Pongo2Render
- type RecoverConfig
- type Renderer
- type Request
- func (r *Request) ContentLength() int
- func (r *Request) FormParams() map[string][]string
- func (r *Request) IsTLS() bool
- func (r *Request) MultipartForm() (*multipart.Form, error)
- func (r *Request) QueryParam(name string) string
- func (r *Request) QueryParams() map[string][]string
- func (r *Request) RealRemoteAddr() string
- func (r *Request) Scheme() string
- func (r *Request) SetBody(reader io.Reader)
- func (r *Request) SetRequest(req *http.Request)
- type Response
- func (resp *Response) CloseNotify() <-chan bool
- func (resp *Response) Committed() bool
- func (resp *Response) Flush()
- func (resp *Response) Header() http.Header
- func (resp *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Response) SetCookie(cookie *http.Cookie)
- func (resp *Response) SetWriter(w http.ResponseWriter)
- func (resp *Response) Size() int64
- func (resp *Response) Status() int
- func (resp *Response) Write(b []byte) (n int, err error)
- func (resp *Response) WriteHeader(code int)
- func (resp *Response) Writer() http.ResponseWriter
- type Route
- type Router
- type SessionConfig
- type Validator
- type VirtRouter
- func Branch(prefix, desc string, nodes ...*VirtRouter) *VirtRouter
- func GetVirtRouter(id string) (*VirtRouter, bool)
- func Leaf(prefix string, apiHandler *ApiHandler, middlewares ...*ApiMiddleware) *VirtRouter
- func NewGroupVirtRouter(prefix, desc string) *VirtRouter
- func NewHandlerVirtRouter(prefix, hid string, middlewares ...MiddlewareConfig) (*VirtRouter, error)
- func RootRouter() *VirtRouter
- func RouterList() []*VirtRouter
- func (vr *VirtRouter) AddChild(virtRouter *VirtRouter) (err error)
- func (vr *VirtRouter) Children() []*VirtRouter
- func (vr *VirtRouter) DelChild(virtRouter *VirtRouter) (err error)
- func (vr *VirtRouter) Delete() (err error)
- func (vr *VirtRouter) Description() string
- func (vr *VirtRouter) Method() string
- func (vr *VirtRouter) Methods() []string
- func (vr *VirtRouter) Params() []Param
- func (vr *VirtRouter) Parent() *VirtRouter
- func (vr *VirtRouter) Path() string
- func (vr *VirtRouter) Progeny() []*VirtRouter
- func (vr *VirtRouter) ResetUse(middlewares []MiddlewareConfig) (err error)
- func (vr *VirtRouter) SetApiHandler(hid string) error
- func (vr *VirtRouter) SetEnable(able bool) (err error)
- func (vr *VirtRouter) SetPrefix(prefix string) (err error)
- func (vr *VirtRouter) Suffix() string
- func (vr *VirtRouter) Use(middlewares ...*ApiMiddleware) *VirtRouter
- type VirtRouterLock
Constants ¶
const ( CONNECT = "CONNECT" DELETE = "DELETE" GET = "GET" HEAD = "HEAD" OPTIONS = "OPTIONS" PATCH = "PATCH" POST = "POST" PUT = "PUT" TRACE = "TRACE" WS = "WS" // websocket "GET" ANY = "*" // exclusion of all methods out of "WS" )
HTTP methods
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types
const ( HeaderAcceptEncoding = "Accept-Encoding" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXForwardedFor = "X-Forwarded-For" HeaderXRealIP = "X-Real-IP" HeaderServer = "Server" HeaderOrigin = "Origin" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" )
Headers
const ( BUSINESS_API_DIR = "BusinessApi" BUSINESS_VIEW_DIR = "BusinessView" SYSTEM_API_DIR = "SystemApi" SYSTEM_VIEW_DIR = "SystemView" STATIC_DIR = "Static" IMG_DIR = STATIC_DIR + "/Img" JS_DIR = STATIC_DIR + "/Js" CSS_DIR = STATIC_DIR + "/Css" TPL_DIR = STATIC_DIR + "/Tpl" PLUGIN_DIR = STATIC_DIR + "/Plugin" UPLOADS_DIR = "Uploads" COMMON_DIR = "Common" MIDDLEWARE_DIR = COMMON_DIR + "/Middleware" TPL_EXT = ".tpl" STATIC_HTML_EXT = ".html" CONFIG_DIR = "Config" APPCONFIG_FILE = CONFIG_DIR + "/app.config" DBCONFIG_FILE = CONFIG_DIR + "/db.config" DB_DIR = COMMON_DIR + "/DB" DEFAULTDB_SECTION = "defaultdb" VIEW_PKG = "/View" MODULE_SUFFIX = "Module" )
项目固定目录文件名称
const ( NAME = "Lessgo" VERSION = "0.5.0" ADDRESS = "https://github.com/lessgo/lessgo" )
const ( ROOT int = iota GROUP HANDLER )
虚拟路由节点类型
const (
MB = 1 << 20
)
Variables ¶
var ( ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType) ErrNotFound = NewHTTPError(http.StatusNotFound) ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") )
Errors
var ( // AppConfig is the instance of Config, store the config information from file AppConfig = initConfig() // GlobalSessions is the instance for the session manager GlobalSessions *session.Manager )
var DefLessgo = newLessgo()
初始化全局Lessgo实例
var (
MaxMemory int64 = 32 << 20
)
文件上传默认内存缓存大小,默认值是 1 << 32 (32MB)。
var Md5 = func() string { file, _ := exec.LookPath(os.Args[0]) info, _ := os.Stat(file) return utils.MakeUnique(info.ModTime()) }()
* 软件自身md5
Functions ¶
func ContentTypeByExtension ¶
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 LoadAppConfig ¶
func LoadAppConfig() (err error)
func LoadDBConfig ¶
func LoadDBConfig() (err error)
func SimpleToken6238 ¶
Types ¶
type ApiHandler ¶
type ApiHandler struct { Desc string // 本操作的描述 Method string // 请求方法,"*"表示除"WS"外全部方法 Params []Param // 参数说明列表,path参数类型的先后顺序与url中保持一致 // Produces []string // 支持的响应内容类型,如["application/xml", "application/json"] Handler func(Context) error // 操作 // contains filtered or unexported fields }
func NilApiHandler ¶
func NilApiHandler(desc string) *ApiHandler
func (*ApiHandler) Methods ¶
func (a *ApiHandler) Methods() []string
真实的请求方法列表(自动转换: "WS"->"GET", "*"->methods)
type ApiMiddleware ¶
type ApiMiddleware struct { Name string // 全局唯一 Desc string DefaultConfig interface{} // 默认配置(JSON格式) Middleware interface{} // MiddlewareFunc or func(configJSON string) MiddlewareFunc // contains filtered or unexported fields }
一旦注册,不可再更改
func (*ApiMiddleware) GetMiddlewareFunc ¶
func (a *ApiMiddleware) GetMiddlewareFunc(config string) MiddlewareFunc
获取中间件
type CommMsg ¶
type CommMsg struct { Code int `json:"code"` Info interface{} `json:"info"` }
Common message format of JSON and JSONP.
type ConfMiddlewareFunc ¶
type ConfMiddlewareFunc func(configJSON string) MiddlewareFunc
支持配置的中间件
func (ConfMiddlewareFunc) GetMiddlewareFunc ¶
func (c ConfMiddlewareFunc) GetMiddlewareFunc(config string) MiddlewareFunc
type Config ¶
type Config struct { AppName string // Application name Info Info // Application info Debug bool // enable/disable debug mode. CrossDomain bool RouterCaseSensitive bool // 是否路由忽略大小写匹配,默认是 true,区分大小写 MaxMemoryMB int64 // 文件上传默认内存缓存大小,单位MB Listen Listen Session SessionConfig Log LogConfig FileCache FileCacheConfig DefaultDB string DBList map[string]DBConfig }
Config is the main struct for BConfig
type Context ¶
type Context interface { netContext.Context // NetContext returns `http://blog.golang.org/context.Context` interface. NetContext() netContext.Context // SetNetContext sets `http://blog.golang.org/context.Context` interface. SetNetContext(netContext.Context) // About Socket's methods. Socket() *websocket.Conn SetSocket(*websocket.Conn) WsRecvJSON(interface{}) error WsRecvMsg(*string) error WsSendJSON(interface{}) (int, error) WsSendMsg(string) (int, error) // Request returns `engine.Request` interface. Request() *Request // Request returns `engine.Response` interface. Response() *Response // Path returns the registered path for the handler. Path() string // SetPath sets the registered path for the handler. SetPath(string) // P returns path parameter by index. P(int) string // Param returns path parameter by name. Param(string) string // ParamNames returns path parameter names. ParamNames() []string // ParamValues returns path parameter values. ParamValues() []string // SetParam sets path parameter. SetParam(name, value string) // QueryParam returns the query param for the provided name. It is an alias // for `engine.URL#QueryParam()`. QueryParam(string) string // QueryParams returns the query parameters as map. // It is an alias for `engine.URL#QueryParams()`. QueryParams() map[string][]string // FormValue returns the form field value for the provided name. It is an // alias for `engine.Request#FormValue()`. FormValue(string) string // FormParams returns the form parameters as map. // It is an alias for `engine.Request#FormParams()`. FormParams() map[string][]string // FormFile returns the multipart form file for the provided name. It is an // alias for `engine.Request#FormFile()`. FormFile(string) (*multipart.FileHeader, error) // MultipartForm returns the multipart form. // It is an alias for `engine.Request#MultipartForm()`. MultipartForm() (*multipart.Form, error) // Cookie returns the named cookie provided in the request. // It is an alias for `engine.Request#Cookie()`. Cookie(string) (*http.Cookie, error) // SetCookie adds a `Set-Cookie` header in HTTP response. // It is an alias for `engine.Response#SetCookie()`. SetCookie(*http.Cookie) // Cookies returns the HTTP cookies sent with the request. // It is an alias for `engine.Request#Cookies()`. Cookies() []*http.Cookie // CruSession returns session data store. CruSession() session.Store // SetSession puts value into session. SetSession(name interface{}, value interface{}) // GetSession gets value from session. GetSession(name interface{}) interface{} // DelSession removes value from session. DelSession(name interface{}) // SessionRegenerateID regenerates session id for this session. // the session data have no changes. SessionRegenerateID() // DestroySession cleans session data and session cookie. DestroySession() // Get retrieves data from the context. Get(string) interface{} // Set saves data in the context. Set(string, interface{}) // Del deletes data from the context. Del(string) // Exists checks if that key exists in the context. Exists(string) bool // Bind binds the request body into provided type `i`. The default binder // does it based on Content-Type header. Bind(interface{}) error // Render renders a template with data and sends a text/html response with status // code. Templates can be registered using `Echo.SetRenderer()`. Render(int, string, interface{}) error // HTML sends an HTTP response with status code. HTML(int, string) error // String sends a string response with status code. String(int, string) error // JSON sends a JSON response with status code. JSON(int, interface{}) error // JSONMsg sends a JSON response with common message format. JSONMsg(code int, msgcode int, info interface{}) error // JSONBlob sends a JSON blob response with status code. JSONBlob(int, []byte) error // JSONP sends a JSONP response with status code. It uses `callback` to construct // the JSONP payload. JSONP(int, string, interface{}) error // JSONPMsg sends a JSONP response with common message format. JSONPMsg(code int, callback string, msgcode int, info interface{}) error // XML sends an XML response with status code. XML(int, interface{}) error // XMLBlob sends a XML blob response with status code. XMLBlob(int, []byte) error // File sends a response with the content of the file. File(string) error // Attachment sends a response from `io.ReaderSeeker` as attachment, prompting // client to save the file. Attachment(io.ReadSeeker, string) error // NoContent sends a response with no body and a status code. NoContent(int) error // Redirect redirects the request with status code. Redirect(int, string) error // Error invokes the registered HTTP error handler. Generally used by middleware. Error(err error) // Handler returns the matched handler by router. Handler() HandlerFunc // SetHandler sets the matched handler by router. SetHandler(HandlerFunc) // Logger returns the `Logger` instance. Logger() logs.Logger // App returns the `Echo` instance. App() *Echo // ServeContent sends static content from `io.Reader` and handles caching // via `If-Modified-Since` request header. It automatically sets `Content-Type` // and `Last-Modified` response headers. ServeContent(io.ReadSeeker, string, time.Time) error // contains filtered or unexported methods }
Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.
type DBConfig ¶
type DBConfig struct { Name string Driver string // Driver:mssql | odbc(mssql) | mysql | mymysql | postgres | sqlite3 | oci8 | goracle ConnString string MaxOpenConns int MaxIdleConns int TableFix string // 表命名空间是前缀还是后缀:prefix | suffix TableSpace string // 表命名空间 TableSnake bool // 表名使用snake风格或保持不变 ColumnFix string // 列命名空间是前缀还是后缀:prefix | suffix ColumnSpace string // 列命名空间 ColumnSnake bool // 列名使用snake风格或保持不变 DisableCache bool ShowExecTime bool ShowSql bool }
DataBase connection Config
type Echo ¶
type Echo struct {
// contains filtered or unexported fields
}
Echo is the top-level framework instance.
func (*Echo) AddLogAdapter ¶
AddLogger provides a given logger adapter intologs.Logger with config string. config need to be correct JSON as string: {"interval":360}.
func (*Echo) AfterUse ¶
func (e *Echo) AfterUse(middleware ...MiddlewareFunc)
AfterUse adds middlewares to the chain which is run after router.
func (*Echo) Any ¶
func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Echo) BeforeUse ¶
func (e *Echo) BeforeUse(middleware ...MiddlewareFunc)
BeforeUse adds middlewares to the chain which is run before router.
func (*Echo) CaseSensitive ¶
func (*Echo) Connect ¶
func (e *Echo) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
Connect registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) DefaultHTTPErrorHandler ¶
DefaultHTTPErrorHandler invokes the default HTTP error handler.
func (*Echo) Delete ¶
func (e *Echo) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
Delete registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) File ¶
func (e *Echo) File(path, file string, middleware ...MiddlewareFunc)
File registers a new route with path to serve a static file.
func (*Echo) Get ¶
func (e *Echo) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
Get registers a new GET route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) GetContext ¶
GetContext returns `Context` from the sync.Pool. You must return the context by calling `PutContext()`.
func (*Echo) Group ¶
func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group)
Group creates a new router group with prefix and optional group-level middleware.
func (*Echo) Head ¶
func (e *Echo) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
Head registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) LogFuncCallDepth ¶
LogFuncCallDepth enable log funcCallDepth.
func (*Echo) Match ¶
func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Echo) MemoryCacheEnable ¶
func (*Echo) NewContext ¶
NewContext returns a Context instance.
func (*Echo) Options ¶
func (e *Echo) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
Options registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) Patch ¶
func (e *Echo) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
Patch registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) Post ¶
func (e *Echo) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
Post registers a new POST route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) PreUse ¶
func (e *Echo) PreUse(middleware ...MiddlewareFunc)
PreUse adds middlewares to the beginning of chain.
func (*Echo) Put ¶
func (e *Echo) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
Put registers a new PUT route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) PutContext ¶
PutContext returns `Context` instance back to the sync.Pool. You must call it after `GetContext()`.
func (*Echo) Run ¶
func (e *Echo) Run(address, tlsCertfile, tlsKeyfile string, readTimeout, writeTimeout time.Duration, graceful bool)
Run starts the HTTP server.
func (*Echo) ServeHTTP ¶
func (e *Echo) ServeHTTP(rw http.ResponseWriter, req *http.Request)
ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (*Echo) SetCaseSensitive ¶
func (*Echo) SetHTTPErrorHandler ¶
func (e *Echo) SetHTTPErrorHandler(h HTTPErrorHandler)
SetHTTPErrorHandler registers a custom Echo.HTTPErrorHandler.
func (*Echo) SetLogLevel ¶
SetLogLevel sets the log level for the logger
func (*Echo) SetMemoryCache ¶
func (e *Echo) SetMemoryCache(m *MemoryCache)
func (*Echo) SetRenderer ¶
SetRenderer registers an HTML template renderer. It's invoked by `Context#Render()`.
func (*Echo) SetSessions ¶
func (*Echo) Static ¶
func (e *Echo) Static(prefix, root string, middleware ...MiddlewareFunc)
Static registers a new route with path prefix to serve static files from the provided root directory.
func (*Echo) SufUse ¶
func (e *Echo) SufUse(middleware ...MiddlewareFunc)
SufUse adds middlewares to the end of chain.
func (*Echo) Trace ¶
func (e *Echo) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
Trace registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.
func (*Echo) URI ¶
func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string
URI generates a URI from handler.
func (*Echo) URL ¶
func (e *Echo) URL(h HandlerFunc, params ...interface{}) string
URL is an alias for `URI` function.
func (*Echo) WebSocket ¶
func (e *Echo) WebSocket(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
WebSocket adds a WebSocket route > handler to the router.
type FileCacheConfig ¶
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common middlware or functionality that should be separate from the parent echo instance while still inheriting from it.
func (*Group) Any ¶
func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Any implements `Echo#Any()` for sub-routes within the Group.
func (*Group) Connect ¶
func (g *Group) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
Connect implements `Echo#Connect()` for sub-routes within the Group.
func (*Group) Delete ¶
func (g *Group) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
Delete implements `Echo#Delete()` for sub-routes within the Group.
func (*Group) Get ¶
func (g *Group) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
Get implements `Echo#Get()` for sub-routes within the Group.
func (*Group) Group ¶
func (g *Group) Group(prefix string, m ...MiddlewareFunc) *Group
Group creates a new sub-group with prefix and optional sub-group-level middleware.
func (*Group) Head ¶
func (g *Group) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
Head implements `Echo#Head()` for sub-routes within the Group.
func (*Group) Match ¶
func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Match implements `Echo#Match()` for sub-routes within the Group.
func (*Group) Options ¶
func (g *Group) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
Options implements `Echo#Options()` for sub-routes within the Group.
func (*Group) Patch ¶
func (g *Group) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
Patch implements `Echo#Patch()` for sub-routes within the Group.
func (*Group) Post ¶
func (g *Group) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
Post implements `Echo#Post()` for sub-routes within the Group.
func (*Group) Put ¶
func (g *Group) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
Put implements `Echo#Put()` for sub-routes within the Group.
func (*Group) Trace ¶
func (g *Group) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
Trace implements `Echo#Trace()` for sub-routes within the Group.
func (*Group) Use ¶
func (g *Group) Use(m ...MiddlewareFunc)
Use implements `Echo#Use()` for sub-routes within the Group.
type HTTPError ¶
HTTPError represents an error that occured while handling a request.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError instance.
type HTTPErrorHandler ¶
HTTPErrorHandler is a centralized HTTP error handler.
type HandlerFunc ¶
HandlerFunc defines a function to server HTTP requests.
type Listen ¶
type Listen struct { Graceful bool // Graceful means use graceful module to start the server Address string ReadTimeout int64 WriteTimeout int64 EnableHTTPS bool HTTPSKeyFile string HTTPSCertFile string }
Listen holds for http and https related config
type MemoryCache ¶
func NewMemoryCache ¶
func NewMemoryCache(singleFileAllow, maxCap int64, gc time.Duration) *MemoryCache
func (*MemoryCache) Enable ¶
func (m *MemoryCache) Enable() bool
func (*MemoryCache) GetCacheFile ¶
func (*MemoryCache) SetEnable ¶
func (m *MemoryCache) SetEnable(bl bool)
type Middleware ¶
type Middleware interface {
GetMiddlewareFunc(config string) MiddlewareFunc
}
中间件接口
type MiddlewareConfig ¶
type MiddlewareConfig struct { Name string `json:"name"` // 全局唯一 Config string `json:"config"` // JSON格式的配置(可选) }
虚拟路由中中间件配置信息,用于获取中间件函数
type MiddlewareFunc ¶
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc defines a function to process middleware.
func Recover ¶
func Recover(configJSON string) MiddlewareFunc
RecoverWithConfig returns a recover middleware from config. See `Recover()`.
func RequestLogger ¶
func RequestLogger(config string) MiddlewareFunc
RequestLogger returns a middleware that logs HTTP requests.
func WrapMiddleware ¶
func WrapMiddleware(h interface{}) MiddlewareFunc
WrapMiddleware wrap `echo.HandlerFunc` into `echo.MiddlewareFunc`.
func (MiddlewareFunc) GetMiddlewareFunc ¶
func (m MiddlewareFunc) GetMiddlewareFunc(_ string) MiddlewareFunc
type Pongo2Render ¶
type Pongo2Render struct {
// contains filtered or unexported fields
}
Pongo2Render is a custom lessgo template renderer using Pongo2.
func NewPongo2Render ¶
func NewPongo2Render(debug bool) *Pongo2Render
New creates a new Pongo2Render instance with custom Options.
type RecoverConfig ¶
type RecoverConfig struct { // StackSize is the stack size to be printed. // Optional with default value as 4k. StackSize int // DisableStackAll disables formatting stack traces of all other goroutines // into buffer after the trace for the current goroutine. // Optional with default value as false. DisableStackAll bool // DisablePrintStack disables printing stack trace. // Optional with default value as false. DisablePrintStack bool }
RecoverConfig defines the config for recover middleware.
type Request ¶
func NewRequest ¶
NewRequest creates a new instance of Request.
func (*Request) ContentLength ¶
func (*Request) FormParams ¶
func (*Request) QueryParam ¶
func (*Request) QueryParams ¶
func (*Request) RealRemoteAddr ¶
func (*Request) SetRequest ¶
SetRequest sets the http.Request instance for this Request.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See http.ResponseWriter(https://golang.org/pkg/net/http/#ResponseWriter)
func NewResponse ¶
func NewResponse(w http.ResponseWriter) *Response
NewResponse creates a new instance of Response.
func (*Response) CloseNotify ¶
CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)
func (*Response) Flush ¶
func (resp *Response) Flush()
Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)
func (*Response) Header ¶
Header returns the header map for the writer that will be sent by WriteHeaderesp. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example [ResponseWriteresp.Trailers](https://golang.org/pkg/net/http/#example_ResponseWriter_trailers)
func (*Response) Hijack ¶
Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)
func (*Response) SetCookie ¶
SetCookie adds a Set-Cookie header. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*Response) SetWriter ¶
func (resp *Response) SetWriter(w http.ResponseWriter)
SetWriter sets the http.ResponseWriter instance for this Response.
func (*Response) Write ¶
Write wraps and implements the http.Response.Write specification. Additionally, Write will increment the size of the current response. See http.Response.Write(https://golang.org/pkg/net/http/#Response.Write)
func (*Response) WriteHeader ¶
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
func (*Response) Writer ¶
func (resp *Response) Writer() http.ResponseWriter
Writer returns the http.ResponseWriter instance for this Response.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is the registry of all registered routes for an `Echo` instance for request matching and URL path parameter parsing.
func (*Router) Add ¶
func (r *Router) Add(method, path string, h HandlerFunc, e *Echo)
Add registers a new route for method and path with matching handler.
func (*Router) Find ¶
Find lookup a handler registed for method and path. It also parses URL for path parameters and load them into context.
For performance:
- Get context from `Echo#GetContext()` - Reset it `Context#Reset()` - Return it `Echo#PutContext()`.
func (*Router) Process ¶
func (r *Router) Process(next HandlerFunc) HandlerFunc
Process implements `echo.MiddlewareFunc` which makes router a middleware.
type SessionConfig ¶
type SessionConfig struct { SessionOn bool SessionProvider string SessionName string SessionGCMaxLifetime int64 SessionProviderConfig string SessionCookieLifeTime int SessionAutoSetCookie bool SessionDomain string EnableSidInHttpHeader bool // enable store/get the sessionId into/from http headers SessionNameInHttpHeader string EnableSidInUrlQuery bool // enable get the sessionId from Url Query params }
SessionConfig holds session related config
type Validator ¶
type Validator interface {
Validate() error
}
Validator is the interface that wraps the Validate function.
type VirtRouter ¶
type VirtRouter struct { Id string `json:"id" xorm:"not null pk VARCHAR(36)"` // UUID Pid string `json:"pid" xorm:"VARCHAR(36)"` // 父节点id Type int `json:"type" xorm:"not null TINYINT(1)"` // 操作类型: 根目录/路由分组/操作 Prefix string `json:"prefix" xorm:"not null VARCHAR(500)"` // 路由节点的url前缀(不含参数) Middlewares []MiddlewareConfig `json:"middlewares" xorm:"TEXT json"` // 中间件列表 (允许运行时修改) Enable bool `json:"enable" xorm:"not null TINYINT(1)"` // 是否启用当前路由节点 Dynamic bool `json:"dynamic" xorm:"not null TINYINT(1)"` // 是否动态追加的节点 Hid string `json:"hid" xorm:"not null VARCHAR(500)"` // 操作ApiHandler.id // contains filtered or unexported fields }
虚拟路由
func Branch ¶
func Branch(prefix, desc string, nodes ...*VirtRouter) *VirtRouter
配置路由分组(必须在init()中调用)
func Leaf ¶
func Leaf(prefix string, apiHandler *ApiHandler, middlewares ...*ApiMiddleware) *VirtRouter
配置路由操作(必须在init()中调用)
func NewHandlerVirtRouter ¶
func NewHandlerVirtRouter(prefix, hid string, middlewares ...MiddlewareConfig) (*VirtRouter, error)
创建虚拟路由动态操作
func (*VirtRouter) AddChild ¶
func (vr *VirtRouter) AddChild(virtRouter *VirtRouter) (err error)
添加子节点
func (*VirtRouter) DelChild ¶
func (vr *VirtRouter) DelChild(virtRouter *VirtRouter) (err error)
删除子节点
func (*VirtRouter) Methods ¶
func (vr *VirtRouter) Methods() []string
真实的请求方法列表(自动转换: "WS"->"GET", "*"->methods)
func (*VirtRouter) ResetUse ¶
func (vr *VirtRouter) ResetUse(middlewares []MiddlewareConfig) (err error)
重置中间件
func (*VirtRouter) SetPrefix ¶
func (vr *VirtRouter) SetPrefix(prefix string) (err error)
设置虚拟路由节点url前缀
func (*VirtRouter) Suffix ¶
func (vr *VirtRouter) Suffix() string
func (*VirtRouter) Use ¶
func (vr *VirtRouter) Use(middlewares ...*ApiMiddleware) *VirtRouter
配置中间件(仅在源码中使用)
type VirtRouterLock ¶
type VirtRouterLock struct {
Md5 string `json:"Md5" xorm:"not null VARCHAR(500)"`
}
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package cache provide a Cache interface and some implemetn engine Usage:
|
Package cache provide a Cache interface and some implemetn engine Usage: |
memcache
Package memcache for cache provider
|
Package memcache for cache provider |
redis
Package redis for cache provider
|
Package redis for cache provider |
Package config is used to parse config Usage: import(
|
Package config is used to parse config Usage: import( |
xml
Package xml for config provider
|
Package xml for config provider |
xml/x2j
Unmarshal dynamic / arbitrary XML docs and extract values (using wildcards, if necessary).
|
Unmarshal dynamic / arbitrary XML docs and extract values (using wildcards, if necessary). |
yaml
Package yaml for config provider
|
Package yaml for config provider |
* | |
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
|
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/ |
Package logs provide a general log interface Usage:
|
Package logs provide a general log interface Usage: |
A Django-syntax like template-engine
|
A Django-syntax like template-engine |
Package session provider
|
Package session provider |
couchbase
Package couchbase for session provider
|
Package couchbase for session provider |
ledis
Package ledis provide session Provider
|
Package ledis provide session Provider |
memcache
Package memcache for session provider
|
Package memcache for session provider |
mysql
Package mysql for session provider
|
Package mysql for session provider |
postgres
Package postgres for session provider
|
Package postgres for session provider |
redis
Package redis for session provider
|
Package redis for session provider |
https://github.com/srcgo/go-otp Package token implements one-time-password generators used in 2-factor authentication systems like RSA-tokens and Google Authenticator.
|
https://github.com/srcgo/go-otp Package token implements one-time-password generators used in 2-factor authentication systems like RSA-tokens and Google Authenticator. |
uuid
Package uuid generates and inspects UUIDs.
|
Package uuid generates and inspects UUIDs. |
Package validation for validations
|
Package validation for validations |
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.
|
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455. |