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(middlewares ...interface{}) error
- func BeforeUse(middlewares ...interface{}) error
- func CleanPath(p string) string
- func ContentTypeByExtension(name string) (t string)
- func Debug() bool
- func DisableServer()
- func EnableServer()
- func File(path, file string, middlewares ...interface{}) error
- func GetHome() string
- func MemoryCacheEnable() bool
- func PreUse(middlewares ...interface{}) error
- func ReadSingleConfig(section string, p interface{}, iniconf confpkg.Configer)
- func ReregisterRouter()
- func ResetAfter()
- func ResetBefore()
- func ResetFiles()
- func ResetStatics()
- func Root(nodes ...*VirtRouter)
- func Run()
- func ServerEnable() bool
- func Sessions() *session.Manager
- func SetBinder(b Binder)
- func SetDebug(on bool)
- func SetHome(homeurl string)
- func SetInternalServerError(fn func(c *Context, err error, rcv interface{}))
- func SetMemoryCache(m *MemoryCache)
- func SetMethodNotAllowed(fn func(*Context) error)
- func SetNotFound(fn func(*Context) error)
- func SetRenderer(r Renderer)
- func Static(prefix, root string, middlewares ...interface{}) error
- func SufUse(middlewares ...interface{}) error
- func WriteSingleConfig(section string, p interface{}, iniconf confpkg.Configer)
- type ApiHandler
- type ApiMiddleware
- type App
- func (this *App) Debug() bool
- func (this *App) Log() logs.Logger
- func (this *App) MemoryCacheEnable() bool
- func (this *App) RealRoutes() []Route
- func (this *App) ServeHTTP(rw http.ResponseWriter, req *http.Request)
- func (this *App) Sessions() *session.Manager
- func (this *App) SetBinder(b Binder)
- func (this *App) SetDebug(on bool)
- func (this *App) SetInternalServerError(fn func(*Context, error, interface{}))
- func (this *App) SetMemoryCache(m *MemoryCache)
- func (this *App) SetMethodNotAllowed(fn func(*Context) error)
- func (this *App) SetNotFound(fn func(*Context) error)
- func (this *App) SetRenderer(r Renderer)
- type Binder
- type Cachefile
- type CommMsg
- type ConfMiddlewareFunc
- type Context
- func (c *Context) Attachment(r io.ReadSeeker, name string) (err error)
- func (c *Context) Bind(i interface{}) error
- func (c *Context) Contains(key string) bool
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) CruSession() session.Store
- func (c *Context) Del(key string)
- func (c *Context) DelSession(name interface{})
- func (c *Context) DestroySession()
- func (c *Context) Error(err error)
- func (c *Context) File(file string) error
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormParams() url.Values
- func (c *Context) FormValue(name string) string
- func (c *Context) Get(key string) interface{}
- func (c *Context) GetSession(name interface{}) interface{}
- func (c *Context) HTML(code int, html string) (err error)
- func (c *Context) IsTLS() bool
- func (c *Context) JSON(code int, i interface{}) (err error)
- func (c *Context) JSONBlob(code int, b []byte) (err error)
- func (c *Context) JSONMsg(code int, msgcode int, info interface{}) (err error)
- func (c *Context) JSONP(code int, callback string, i interface{}) (err error)
- func (c *Context) JSONPMsg(code int, callback string, msgcode int, info interface{}) (err error)
- func (c *Context) Log() logs.Logger
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) NoContent(code int) error
- func (c *Context) P(i int) (value string)
- func (c *Context) Param(name string) (value string)
- func (c *Context) ParamNames() []string
- func (c *Context) ParamValues() []string
- func (c *Context) Path() string
- func (c *Context) QueryParam(name string) string
- func (c *Context) QueryParams() url.Values
- func (c *Context) RealRemoteAddr() string
- func (c *Context) Redirect(code int, url string) error
- func (c *Context) Render(code int, name string, data interface{}) (err error)
- func (c *Context) Request() *http.Request
- func (c *Context) Response() *Response
- func (c *Context) Scheme() string
- func (c *Context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error
- func (c *Context) SessionRegenerateID()
- func (c *Context) Set(key string, val interface{})
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetParam(name, value string)
- func (c *Context) SetPath(p string)
- func (c *Context) SetRequestBody(reader io.Reader)
- func (c *Context) SetSession(name interface{}, value interface{})
- func (c *Context) SetSocket(conn *websocket.Conn)
- func (c *Context) Socket() *websocket.Conn
- func (c *Context) String(code int, s string) (err error)
- func (c *Context) WsRecvJSON(v interface{}) error
- func (c *Context) WsRecvMsg(v *string) error
- func (c *Context) WsSendJSON(v interface{}) (int, error)
- func (c *Context) WsSendMsg(v string) (int, error)
- func (c *Context) XML(code int, i interface{}) (err error)
- func (c *Context) XMLBlob(code int, b []byte) (err error)
- type FileCacheConfig
- type Group
- type HTTPError
- type HandlerFunc
- type Info
- type Lessgo
- type Listen
- type LogConfig
- type MemoryCache
- type Middleware
- type MiddlewareConfig
- type MiddlewareFunc
- type Param
- type Pongo2Render
- type RecoverConfig
- type Renderer
- 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 VirtFile
- 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 VirtRoutes() []*VirtRouter
- func (vr *VirtRouter) AddChild(virtRouter *VirtRouter) (err error)
- func (vr *VirtRouter) DelChild(virtRouter *VirtRouter) (err error)
- func (vr *VirtRouter) Delete() (err error)
- func (vr *VirtRouter) Description() string
- func (vr *VirtRouter) Methods() []string
- func (vr *VirtRouter) Params() []Param
- func (vr *VirtRouter) Path() string
- func (vr *VirtRouter) Progeny() []*VirtRouter
- func (vr *VirtRouter) ResetUse(middlewares []*MiddlewareConfig) (err error)
- func (vr *VirtRouter) SetApiHandler(hid string) (err 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 VirtStatic
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" HeaderXCSRFToken = "X-CSRF-Token" )
Headers
const ( BIZ_HANDLER_DIR = "bizhandler" BIZ_MODEL_DIR = "bizmodel" BIZ_VIEW_DIR = "bizview" SYS_HANDLER_DIR = "syshandler" SYS_MODEL_DIR = "sysmodel" SYS_VIEW_DIR = "sysview" 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 = "middleware" ROUTER_DIR = "router" TPL_EXT = ".tpl" STATIC_HTML_EXT = ".html" CONFIG_DIR = "config" APPCONFIG_FILE = CONFIG_DIR + "/app.config" ROUTERCONFIG_FILE = CONFIG_DIR + "/virtrouter.config" LOG_FILE = "logger/lessgo.log" )
项目固定目录文件名称
const ( NAME = "Lessgo" VERSION = "0.7.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) ErrStatusInternalServerError = NewHTTPError(http.StatusInternalServerError) ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") )
Errors
var ( // 全局配置实例 Config = newConfig() // 全局运行日志实例(来自数据库的日志除外) Log = func() logs.Logger { l := logs.NewLogger(1000) l.AddAdapter("console", "") l.AddAdapter("file", `{"filename":"`+LOG_FILE+`"}`) return l }() // 软件自身md5值 Md5 = func() string { file, _ := exec.LookPath(os.Args[0]) info, _ := os.Stat(file) return utils.MakeUnique(info.ModTime()) }() )
var AutoHTMLSuffix = ApiMiddleware{ Name: "智能追加.html后缀", Desc: "静态路由时智能追加\".html\"后缀", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) (err error) { p := c.Request().URL.Path if p[len(p)-1] != '/' { ext := path.Ext(p) if ext == "" || ext[0] != '.' { c.Request().URL.Path = strings.TrimSuffix(p, ext) + STATIC_HTML_EXT + ext c.ParamValues()[0] += STATIC_HTML_EXT } } return next(c) } }, }.Reg()
var CheckHome = ApiMiddleware{ Name: "检查是否为访问主页", Desc: "检查是否为访问主页", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) error { if c.Request().URL.Path == "/" { c.Request().URL.Path = GetHome() } return next(c) } }, }.Reg()
var CheckServer = ApiMiddleware{ Name: "检查服务器是否启用", Desc: "检查服务器是否启用", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) error { if !ServerEnable() { return c.NoContent(http.StatusServiceUnavailable) } return next(c) } }, }.Reg()
var CrossDomain = ApiMiddleware{ Name: "设置允许跨域", Desc: "根据配置信息设置允许跨域", Middleware: func(c *Context) error { c.Response().Header().Set("Access-Control-Allow-Origin", "*") return nil }, }.Reg()
var FilterTemplate = ApiMiddleware{ Name: "过滤前端模板", Desc: "过滤前端模板,不允许直接访问", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) (err error) { ext := path.Ext(c.Request().URL.Path) if len(ext) >= 4 && ext[:4] == TPL_EXT { return c.NoContent(http.StatusForbidden) } return next(c) } }, }.Reg()
var ( // 文件上传默认内存缓存大小,默认值是 1 << 32 (32MB)。 MaxMemory int64 = 32 << 20 )
var Recover = ApiMiddleware{ Name: "捕获运行时恐慌", Desc: "Recover returns a middleware which recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.", Config: RecoverConfig{ StackSize: 4 << 10, DisableStackAll: false, DisablePrintStack: false, }, Middleware: func(confObject interface{}) MiddlewareFunc { config := confObject.(RecoverConfig) if config.StackSize == 0 { config.StackSize = 4 << 10 } return func(next HandlerFunc) HandlerFunc { return func(c *Context) error { defer func() { if r := recover(); r != nil { var err error switch r := r.(type) { case error: err = r default: err = fmt.Errorf("%v", r) } stack := make([]byte, config.StackSize) length := runtime.Stack(stack, !config.DisableStackAll) if !config.DisablePrintStack { Log.Error("[%s] %s %s", color.Red("PANIC RECOVER"), err, stack[:length]) } c.Error(err) } }() return next(c) } } }, }.Reg()
var RequestLogger = ApiMiddleware{ Name: "系统运行日志打印", Desc: "RequestLogger returns a middleware that logs HTTP requests.", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) (err error) { if !Debug() { if err := next(c); err != nil { c.Error(err) } return nil } start := time.Now() if err := next(c); err != nil { c.Error(err) } stop := time.Now() method := c.request.Method path := c.request.URL.Path if path == "" { path = "/" } size := c.response.Size() n := c.response.Status() code := color.Green(n) switch { case n >= 500: code = color.Red(n) case n >= 400: code = color.Yellow(n) case n >= 300: code = color.Cyan(n) } Log.Debug("%s | %s | %s | %s | %s | %d", c.RealRemoteAddr(), method, path, code, stop.Sub(start), size) return nil } }, }.Reg()
Functions ¶
func CleanPath ¶ added in v0.7.0
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
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 ReadSingleConfig ¶ added in v0.7.0
func SetInternalServerError ¶ added in v0.7.0
设置请求的操作发生错误后的默认处理(内部有默认实现) 500 Internal Server Error
func SetMethodNotAllowed ¶ added in v0.7.0
设置请求的url存在但方法不被允许时的默认操作(内部有默认实现) 405 Method Not Allowed
func SetNotFound ¶ added in v0.7.0
设置请求的url不存在时的默认操作(内部有默认实现) 404 Not Found
func WriteSingleConfig ¶ added in v0.7.0
Types ¶
type ApiHandler ¶
type ApiHandler struct { Desc string // 本操作的描述 Method string // 请求方法,"*"表示除"WS"外全部方法,多方法写法:"GET|POST"或"GET POST",冲突时优先级WS>GET>* Params []Param // 参数说明列表,path参数类型的先后顺序与url中保持一致 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 Config interface{} // 初始配置,若希望使用参数,则Config不能为nil,至少为对应类型的空值 Middleware interface{} // 处理函数,类型参考上面注释 // contains filtered or unexported fields }
* 中间件 * ApiMiddleware.Middleware 支持的处理函数类型: * MiddlewareFunc * func(HandlerFunc) HandlerFunc * HandlerFunc * func(Context) error * ConfMiddlewareFunc * func(confObject interface{}) MiddlewareFunc
func (*ApiMiddleware) ConfigJSON ¶ added in v0.7.0
func (a *ApiMiddleware) ConfigJSON() string
获取JSON字符串格式的中间件配置
func (*ApiMiddleware) NewMiddlewareConfig ¶ added in v0.7.0
func (a *ApiMiddleware) NewMiddlewareConfig() *MiddlewareConfig
返回中间件配置结构体
func (*ApiMiddleware) SetConfig ¶ added in v0.7.0
func (a *ApiMiddleware) SetConfig(confObject interface{}) *ApiMiddleware
设置默认配置,重置中间件
type App ¶ added in v0.7.0
type App struct {
// contains filtered or unexported fields
}
App is the top-level framework instancthis.
func (*App) MemoryCacheEnable ¶ added in v0.7.0
func (*App) ServeHTTP ¶ added in v0.7.0
func (this *App) ServeHTTP(rw http.ResponseWriter, req *http.Request)
ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (*App) SetBinder ¶ added in v0.7.0
SetBinder registers a custom binder. It's invoked by `Context#Bind()`.
func (*App) SetInternalServerError ¶ added in v0.7.0
func (*App) SetMemoryCache ¶ added in v0.7.0
func (this *App) SetMemoryCache(m *MemoryCache)
func (*App) SetMethodNotAllowed ¶ added in v0.7.0
func (*App) SetNotFound ¶ added in v0.7.0
func (*App) SetRenderer ¶ added in v0.7.0
SetRenderer registers an HTML template renderer. It's invoked by `Context#Render()`.
type CommMsg ¶
type CommMsg struct { Code int `json:"code"` Info interface{} `json:"info,omitempty"` }
Common message format of JSON and JSONP.
type ConfMiddlewareFunc ¶
type ConfMiddlewareFunc func(confObject interface{}) MiddlewareFunc
支持配置的中间件处理函数, 若接收参数类型为字符串,且默认配置Config不为nil,则支持运行时动态配置。
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
func (*Context) Attachment ¶
func (c *Context) Attachment(r io.ReadSeeker, name string) (err error)
Attachment sends a response from `io.ReaderSeeker` as attachment, prompting client to save the file.
func (*Context) Bind ¶
Bind binds the request body into provided type `i`. The default binder does it based on Content-Type header.
func (*Context) CruSession ¶
CruSession returns session data info.
func (*Context) DelSession ¶
func (c *Context) DelSession(name interface{})
DelSession removes value from session.
func (*Context) DestroySession ¶
func (c *Context) DestroySession()
DestroySession cleans session data and session cookie.
func (*Context) Error ¶
Error invokes the registered HTTP error handler. Generally used by middleware.
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the multipart form file for the provided name.
func (*Context) FormParams ¶
FormParams returns the form parameters as map.
func (*Context) GetSession ¶
func (c *Context) GetSession(name interface{}) interface{}
GetSession gets value from session.
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) MultipartForm ¶
MultipartForm returns the multipart form.
func (*Context) ParamNames ¶
ParamNames returns path parameter names.
func (*Context) ParamValues ¶
ParamValues returns path parameter values.
func (*Context) QueryParam ¶
QueryParam returns the query param for the provided name.
func (*Context) QueryParams ¶
QueryParams returns the query parameters.
func (*Context) RealRemoteAddr ¶ added in v0.7.0
func (*Context) Render ¶
Render renders a template with data and sends a text/html response with status code. Templates can be registered using `App.SetRenderer()`.
func (*Context) ServeContent ¶
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.
func (*Context) SessionRegenerateID ¶
func (c *Context) SessionRegenerateID()
SessionRegenerateID regenerates session id for this session. the session data have no changes.
func (*Context) SetRequestBody ¶ added in v0.7.0
func (*Context) SetSession ¶
func (c *Context) SetSession(name interface{}, value interface{})
SetSession puts value into session.
func (*Context) WsRecvJSON ¶
func (*Context) WsSendJSON ¶
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 app instance while still inheriting from it.
type HTTPError ¶
HTTPError represents an error that occured while handling a request.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError instancthis.
type HandlerFunc ¶
HandlerFunc defines a function to server HTTP requests.
type Lessgo ¶
type Lessgo struct { *App // contains filtered or unexported fields }
func (Lessgo) LoadMainConfig ¶ added in v0.7.0
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 MiddlewareConfig ¶
type MiddlewareConfig struct { Name string `json:"name"` // 全局唯一 Config string `json:"config"` // JSON格式的配置(可选) // contains filtered or unexported fields }
虚拟路由中中间件配置信息,用于获取中间件函数
func WrapMiddlewareConfigs ¶ added in v0.7.0
func WrapMiddlewareConfigs(middlewares []interface{}) ([]*MiddlewareConfig, error)
自动转换某些允许的对象为中间件配置类型.
func (*MiddlewareConfig) CheckDynamic ¶ added in v0.7.0
func (m *MiddlewareConfig) CheckDynamic() bool
检查是否支持动态配置
func (*MiddlewareConfig) CheckValid ¶ added in v0.7.0
func (m *MiddlewareConfig) CheckValid() bool
检查是否为有效配置
func (*MiddlewareConfig) GetConfig ¶ added in v0.7.0
func (m *MiddlewareConfig) GetConfig() string
获取JSON字符串格式的中间件配置
func (*MiddlewareConfig) SetConfig ¶ added in v0.7.0
func (m *MiddlewareConfig) SetConfig(configJSONBytes []byte) error
以JSON字节流格式配置中间件
type MiddlewareFunc ¶
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc defines a function to process middleware.
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 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 { // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.NotFound is used. NotFound HandlerFunc // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // If it is not set, http.Error with http.StatusMethodNotAllowed is used. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed HandlerFunc // Function to handle panics recovered from http handlers. // It should be used to generate a error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecovered panics. ErrorPanicHandler func(*Context, error, interface{}) // contains filtered or unexported fields }
Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes
func (*Router) Handle ¶ added in v0.7.0
func (r *Router) Handle(method, path string, handle HandlerFunc)
Handle registers a new request handle with the given path and method.
For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
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 VirtFile ¶ added in v0.7.0
type VirtFile struct { Path string File string Middlewares []*MiddlewareConfig }
单独注册的静态文件虚拟路由(无法在Root()下使用,暂不支持运行时修改)
type VirtRouter ¶
type VirtRouter struct { Id string `json:"id""` // UUID Type int `json:"type""` // 操作类型: 根目录/路由分组/操作 Prefix string `json:"prefix"` // 路由节点的url前缀(不含参数) Middlewares []*MiddlewareConfig `json:"middlewares"` // 中间件列表 (允许运行时修改) Enable bool `json:"enable"` // 是否启用当前路由节点 Dynamic bool `json:"dynamic"` // 是否动态追加的节点 Hid string `json:"hid"` // 操作ApiHandler.id Children virtRouterSlice `json:"children"` // 子节点 Parent *VirtRouter `json:"-"` // 父节点 // contains filtered or unexported fields }
虚拟路由(在Root()下使用,支持运行时修改)
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 VirtRoutes ¶ added in v0.7.0
func VirtRoutes() []*VirtRouter
返回当前虚拟的路由列表(不含单独注册的静态路由VirtFiles/VirtStatics)
func (*VirtRouter) AddChild ¶
func (vr *VirtRouter) AddChild(virtRouter *VirtRouter) (err error)
添加子节点(仅限动态配置时使用)
func (*VirtRouter) DelChild ¶
func (vr *VirtRouter) DelChild(virtRouter *VirtRouter) (err error)
删除子节点(仅限动态配置时使用)
func (*VirtRouter) ResetUse ¶
func (vr *VirtRouter) ResetUse(middlewares []*MiddlewareConfig) (err error)
重置中间件
func (*VirtRouter) SetApiHandler ¶
func (vr *VirtRouter) SetApiHandler(hid string) (err error)
为节点更换操作
func (*VirtRouter) SetPrefix ¶
func (vr *VirtRouter) SetPrefix(prefix string) (err error)
设置虚拟路由节点url前缀
func (*VirtRouter) Use ¶
func (vr *VirtRouter) Use(middlewares ...*ApiMiddleware) *VirtRouter
配置中间件(仅在源码中使用), 因为源码路由书写格式需要,仅允许返回*VirtRouter一个参数, 而动态配置时需要有error反馈因此,该方法仅限源码中使用。
type VirtStatic ¶ added in v0.7.0
type VirtStatic struct { Prefix string Root string Middlewares []*MiddlewareConfig }
单独注册的静态目录虚拟路由(无法在Root()下使用,暂不支持运行时修改)
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
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 |
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. |