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 CanMemoryCache() bool
- func CleanPath(p string) string
- func ContentTypeByExtension(name string) string
- func Debug() bool
- func DisableMemoryCache()
- func DisableServer()
- func EnableMemoryCache()
- func EnableServer()
- func File(path, file string, middlewares ...interface{}) error
- func GetHome() string
- func PreUse(middlewares ...interface{}) error
- func ReadSingleConfig(section string, p interface{}, iniconf confpkg.Configer)
- func RefreshMemoryCache()
- func ReregisterRouter(reasons ...string)
- func ResetAfter()
- func ResetBefore()
- func ResetFiles()
- func ResetStatics()
- func Root(nodes ...*VirtRouter)
- func Run(graceExitCallback ...func() error)
- func ServerEnable() bool
- func Sessions() *session.Manager
- func SetBinder(b Binder)
- func SetDebug(on bool)
- func SetFailureHandler(fn func(c *Context, code int, errString string) error)
- func SetHome(homeurl string)
- func SetPanicStackFunc(fn func(rcv interface{}) string)
- func SetRenderer(r Renderer)
- func Static(prefix, root string, middlewares ...interface{}) error
- func SufUse(middlewares ...interface{}) error
- func TemplateVariable(name string, fn interface{})
- func WriteSingleConfig(section string, p interface{}, iniconf confpkg.Configer)
- type ApiHandler
- type ApiMiddleware
- type App
- func (this *App) CanMemoryCache() bool
- func (this *App) Debug() bool
- func (this *App) IsClose() bool
- func (this *App) Log() logs.Logger
- func (this *App) MemoryCache() *MemoryCache
- 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) SetFailureHandler(fn func(c *Context, code int, errString string) error)
- func (this *App) SetGraceExitFunc(fn func() error)
- func (this *App) SetPanicStackFunc(fn func(rcv interface{}) string)
- func (this *App) SetRenderer(r Renderer)
- func (this *App) SetStatus(serving bool)
- func (this *App) TemplateVariable(name string, fn interface{})
- type Binder
- type Cachefile
- type CommJSON
- type ConfMiddlewareFunc
- type Context
- func (c *Context) AddCookie(cookie *http.Cookie)
- func (c *Context) AddCookieParam(cookie *http.Cookie)
- func (c *Context) AddFormParam(key string, value string)
- func (c *Context) AddHeader(key string, value string)
- func (c *Context) AddHeaderParam(key string, value string)
- func (c *Context) AddQueryParam(key string, value string)
- func (c *Context) Attachment(r io.ReadSeeker, name string) error
- func (c *Context) Bind(container interface{}) error
- func (c *Context) Contains(key string) bool
- func (c *Context) CookieParam(key string) *http.Cookie
- func (c *Context) CookieParams() []*http.Cookie
- func (c *Context) CruSession() session.Store
- func (c *Context) Del(key string)
- func (c *Context) DelCookie()
- func (c *Context) DelHeader(key string)
- func (c *Context) DelSession(key interface{})
- func (c *Context) DestroySession()
- func (c *Context) Failure(code int, err error) error
- func (c *Context) File(file string) error
- func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) FormParam(key string) string
- func (c *Context) FormParams(key string) []string
- func (c *Context) FormValues() url.Values
- func (c *Context) Get(key string) interface{}
- func (c *Context) GetSession(key interface{}) interface{}
- func (c *Context) HTML(code int, html string) error
- func (c *Context) Header() http.Header
- func (c *Context) HeaderParam(key string) string
- func (c *Context) HeaderParams(key string) []string
- func (c *Context) HeaderValues() http.Header
- func (c *Context) IsTLS() bool
- func (c *Context) JSON(code int, i interface{}) error
- func (c *Context) JSONBlob(code int, b []byte) error
- func (c *Context) JSONMsg(code int, msgcode int, info interface{}) error
- func (c *Context) JSONP(code int, callback string, i interface{}) error
- func (c *Context) JSONPMsg(code int, callback string, msgcode int, info interface{}) error
- func (c *Context) Log() logs.Logger
- func (c *Context) Markdown(file string, hasCatalog ...bool) error
- func (c *Context) NoContent(code int) error
- func (c *Context) Path() string
- func (c *Context) PathParam(key string) string
- func (c *Context) PathParamByIndex(i int) string
- func (c *Context) PathParamKeys() []string
- func (c *Context) PathParamValues() []string
- func (c *Context) QueryParam(key string) string
- func (c *Context) QueryParams(key string) []string
- func (c *Context) QueryValues() 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{}) error
- func (c *Context) Request() *http.Request
- func (c *Context) Response() *Response
- func (c *Context) ResponseWriter() http.ResponseWriter
- func (c *Context) ReverseProxy(targetUrlBase string, pathAppend bool) error
- func (c *Context) SaveFile(key string, cover bool, newfname ...string) (fileUrl string, size int64, err error)
- 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) SetFormParam(key string, value string)
- func (c *Context) SetHeader(key string, value string)
- func (c *Context) SetHeaderParam(key string, value string)
- func (c *Context) SetPath(p string)
- func (c *Context) SetPathParam(key, value string)
- func (c *Context) SetQueryParam(key string, value string)
- func (c *Context) SetRequestBody(reader io.Reader)
- func (c *Context) SetResponse(resp *Response)
- func (c *Context) SetSession(key interface{}, value interface{})
- func (c *Context) SetWs(conn *websocket.Conn)
- func (c *Context) String(code int, s string) error
- func (c *Context) Write(b []byte) (int, error)
- func (c *Context) WriteHeader(code int)
- func (c *Context) Ws() *websocket.Conn
- func (c *Context) WsClose() error
- func (c *Context) WsRecvJSON(v interface{}) error
- func (c *Context) WsRecvString(v *string) error
- func (c *Context) WsSendJSON(v interface{}) (int, error)
- func (c *Context) WsSendString(v string) (int, error)
- func (c *Context) XML(code int, i interface{}) error
- func (c *Context) XMLBlob(code int, b []byte) error
- type FailureHandlerFunc
- 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 PanicStackFunc
- type Param
- type Pongo2Render
- type Renderer
- type Response
- func (r *Response) AddCookie(cookie *http.Cookie)
- func (resp *Response) CloseNotify() <-chan bool
- func (resp *Response) Committed() bool
- func (r *Response) DelCookie()
- 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) (int, error)
- func (resp *Response) WriteHeader(code int)
- func (resp *Response) Writer() http.ResponseWriter
- type Result
- type ReverseProxys
- type Route
- type Router
- type SessionConfig
- type Tpl
- type Validator
- type VirtFile
- type VirtRouter
- func Branch(prefix, desc string, nodes ...*VirtRouter) *VirtRouter
- func GetVirtRouter(id string) (*VirtRouter, bool)
- func GetVirtRouterByPath(path 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) GetMiddlewareConfig(name string) (*MiddlewareConfig, bool)
- func (vr *VirtRouter) HTTP200() []Result
- 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 (v *VirtRouter) Sort() *VirtRouter
- 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 = "biz_handler" BIZ_MODEL_DIR = "biz_model" BIZ_VIEW_DIR = "biz_view" SYS_HANDLER_DIR = "sys_handler" SYS_MODEL_DIR = "sys_model" SYS_VIEW_DIR = "sys_view" 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.8" ADDRESS = "https://github.com/henrylee2cn/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 = func() *config { fmt.Printf("%s\n(%s)\n\n", banner, ADDRESS) c := newConfig() err := c.LoadMainConfig() if err != nil { fmt.Println(err) } return c }() // 全局运行日志实例(来自数据库的日志除外) 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) 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.pvalues[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-Credentials", "true") c.response.Header().Set("Access-Control-Allow-Origin", c.HeaderParam("Origin")) return nil }, }.Reg()
var FilterTemplate = ApiMiddleware{ Name: "过滤前端模板", Desc: "过滤前端模板,不允许直接访问", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) 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 ( // 文件上传默认内存缓存大小,默认值是64MB。 MaxMemory int64 = 64 * MB )
var RequestLogger = ApiMiddleware{ Name: "系统运行日志打印", Desc: "RequestLogger returns a middleware that logs HTTP requests.", Middleware: func(next HandlerFunc) HandlerFunc { return func(c *Context) error { var u = c.request.URL.String() start := time.Now() if err := next(c); err != nil { c.Failure(500, err) } stop := time.Now() method := c.request.Method if u == "" { u = "/" } n := c.response.Status() var code string if runtime.GOOS == "linux" { code = strconv.Itoa(n) } else { code = color.Green(n) switch { case n >= 500: code = color.Red(n) case n >= 400: code = color.Magenta(n) case n >= 300: code = color.Cyan(n) } } Log.Debug("%15s | %7s | %s | %8d | %10s | %s", c.RealRemoteAddr(), method, code, c.response.Size(), stop.Sub(start), u) 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 SetFailureHandler ¶ added in v1.0.0
设置失败状态默认的响应操作(内部有默认实现)
func SetPanicStackFunc ¶ added in v1.0.0
func SetPanicStackFunc(fn func(rcv interface{}) string)
设置获取请求过程中恐慌Stack信息的函数(内部有默认实现)
func TemplateVariable ¶ added in v1.0.0
func TemplateVariable(name string, fn interface{})
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中保持一致 HTTP200 []Result // (可选)HTTP Status Code 为200时的响应结果 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 Params []Param // (可选)参数说明列表(应该只声明当前中间件用到的参数),path参数类型的先后顺序与url中保持一致 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) 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) SetFailureHandler ¶ added in v1.0.0
set the default failuer handler.
func (*App) SetGraceExitFunc ¶ added in v1.0.0
Set the graceful exit or restart callback function.
func (*App) SetPanicStackFunc ¶ added in v1.0.0
设置获取请求过程中恐慌Stack信息的函数
func (*App) SetRenderer ¶ added in v0.7.0
SetRenderer registers an HTML template renderer. It's invoked by `Context#Render()`.
func (*App) TemplateVariable ¶ added in v1.0.0
SetRenderer registers an HTML template renderer. It's invoked by `Context#Render()`.
type ConfMiddlewareFunc ¶
type ConfMiddlewareFunc func(confObject interface{}) MiddlewareFunc
支持配置的中间件处理函数, 若接收参数类型为字符串,且默认配置Config不为nil,则支持运行时动态配置。
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
func (*Context) AddCookie ¶ added in v1.0.0
AddCookie adds cookie for response. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*Context) AddCookieParam ¶ added in v1.0.0
AddCookieParam adds a cookie to the request.
func (*Context) AddFormParam ¶ added in v1.0.0
AddFormParam adds the form param. It appends to any existing values associated with key.
func (*Context) AddHeader ¶ added in v1.0.0
AddHeader sets header for response. It appends to any existing values associated with key.
func (*Context) AddHeaderParam ¶ added in v1.0.0
AddHeaderParam sets request header. It appends to any existing values associated with key.
func (*Context) AddQueryParam ¶ added in v1.0.0
AddQueryParam adds the the query param. It appends to any existing values associated with key.
func (*Context) Attachment ¶
func (c *Context) Attachment(r io.ReadSeeker, name string) 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 `container`. The default binder does it based on Content-Type header.
func (*Context) CookieParam ¶ added in v1.0.0
CookieParam returns the named cookie provided in the request.
func (*Context) CookieParams ¶ added in v1.0.0
CookieParams returns the HTTP cookies sent with the request.
func (*Context) CruSession ¶
CruSession returns session data info.
func (*Context) DelCookie ¶ added in v1.0.0
func (c *Context) DelCookie()
DelCookie deletes cookie for response.
func (*Context) DelHeader ¶ added in v1.0.0
DelHeader deletes the values associated with key for response.
func (*Context) DelSession ¶
func (c *Context) DelSession(key interface{})
DelSession removes value from session.
func (*Context) DestroySession ¶
func (c *Context) DestroySession()
DestroySession cleans session data and session cookie.
func (*Context) Failure ¶ added in v1.0.0
Failure writes http failure status, example 403, 404, 405, 500 and so on.
func (*Context) FormParam ¶ added in v1.0.0
FormParam returns the form field value for the provided key.
func (*Context) FormParams ¶
FormParams returns the form field value with "[]string" for the provided key.
func (*Context) FormValues ¶ added in v1.0.0
FormValues returns the form params as url.Values.
func (*Context) GetSession ¶
func (c *Context) GetSession(key interface{}) interface{}
GetSession gets value from session.
func (*Context) HeaderParam ¶ added in v1.0.0
HeaderParam returns request header value for the provided key.
func (*Context) HeaderParams ¶ added in v1.0.0
HeaderParams returns request header value with "[]string" for the provided key.
func (*Context) HeaderValues ¶ added in v1.0.0
HeaderValues returns the request header.
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) Markdown ¶ added in v1.0.0
Markdown parses markdown file and generates html in github style
func (*Context) PathParamByIndex ¶ added in v1.0.0
PathParamByIndex returns path param by index.
func (*Context) PathParamKeys ¶ added in v1.0.0
PathParamKeys returns path param keys.
func (*Context) PathParamValues ¶ added in v1.0.0
PathParamValues returns path param values.
func (*Context) QueryParam ¶
QueryParam returns the query param for the provided key.
func (*Context) QueryParams ¶
QueryParams returns the query param with "[]string".
func (*Context) QueryValues ¶ added in v1.0.0
QueryValues returns all query params.
func (*Context) RealRemoteAddr ¶ added in v0.7.0
获取客户端真实IP
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) ResponseWriter ¶ added in v1.0.0
func (c *Context) ResponseWriter() http.ResponseWriter
func (*Context) ReverseProxy ¶ added in v1.0.0
ReverseProxy routes URLs to the scheme, host, and base path provided in targetUrlBase. If pathAppend is "true" and the targetUrlBase's path is "/base" and the incoming request was for "/dir", the target request will be for /base/dir.
func (*Context) SaveFile ¶ added in v1.0.0
func (c *Context) SaveFile(key string, cover bool, newfname ...string) (fileUrl string, size int64, err error)
SaveFile saves the file *Context.FormFile to UPLOADS_DIR, character "?" indicates that the original file name. for example newfname="a/?" -> UPLOADS_DIR/a/fname.
func (*Context) ServeContent ¶
ServeContent sends static content from `io.ReadSeeker` 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) SetFormParam ¶ added in v1.0.0
SetFormParam sets the form param. It replaces any existing values.
func (*Context) SetHeader ¶ added in v1.0.0
SetHeader sets header for response. It replaces any existing values.
func (*Context) SetHeaderParam ¶ added in v1.0.0
SetHeaderParam sets request header. It replaces any existing values.
func (*Context) SetPathParam ¶ added in v1.0.0
SetPathParam sets path param.
func (*Context) SetQueryParam ¶ added in v1.0.0
SetQueryParam sets the query param. It replaces any existing values.
func (*Context) SetRequestBody ¶ added in v0.7.0
func (*Context) SetResponse ¶ added in v1.0.0
func (*Context) SetSession ¶
func (c *Context) SetSession(key interface{}, value interface{})
SetSession puts value into session.
func (*Context) Write ¶ added in v1.0.0
Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.
func (*Context) WriteHeader ¶ added in v1.0.0
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 (*Context) WsRecvString ¶ added in v1.0.0
接收string格式的websocket信息
func (*Context) WsSendJSON ¶
发送JSON格式的websocket信息
func (*Context) WsSendString ¶ added in v1.0.0
发送string格式的websocket信息
type FailureHandlerFunc ¶ added in v1.0.0
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
func (this Lessgo) LoadMainConfig() (err error)
type Listen ¶
type Listen struct { Address string ReadTimeout int64 WriteTimeout int64 EnableTLS bool TLSAddress string 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) GetApiMiddleware ¶ added in v1.0.0
func (m *MiddlewareConfig) GetApiMiddleware() *ApiMiddleware
获取*ApiMiddleware
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 PanicStackFunc ¶ added in v1.0.0
type PanicStackFunc func(rcv interface{}) string
type Pongo2Render ¶
Pongo2Render is a custom lessgo template renderer using Pongo2.
func NewPongo2Render ¶
func NewPongo2Render(caching bool) *Pongo2Render
New creates a new Pongo2Render instance with custom Options.
func (*Pongo2Render) FromCache ¶ added in v1.0.0
func (p *Pongo2Render) FromCache(fname string) (*pongo2.Template, error)
func (*Pongo2Render) TemplateVariable ¶ added in v1.0.0
func (p *Pongo2Render) TemplateVariable(name string, v interface{})
type Renderer ¶
type Renderer interface { Render(io.Writer, string, interface{}, *Context) error TemplateVariable(name string, v interface{}) }
Renderer is the interface that wraps the Render function.
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) AddCookie ¶ added in v1.0.0
AddCookie adds a Set-Cookie header. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
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.
func (*Response) DelCookie ¶ added in v1.0.0
func (r *Response) DelCookie()
DelCookie sets Set-Cookie header.
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.
func (*Response) Header ¶
Header returns the header map that will be sent by WriteHeader. 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.
func (*Response) Hijack ¶
Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection.
func (*Response) SetWriter ¶
func (resp *Response) SetWriter(w http.ResponseWriter)
SetWriter sets the http.ResponseWriter instance for this Response.
func (*Response) Write ¶
Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.
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 Result ¶ added in v1.0.0
type Result struct { Code int `json:"code"` // (必填)返回结果码 Info interface{} `json:"info,omitempty"` // (可选)返回结果格式参考或描述 }
type ReverseProxys ¶ added in v1.0.0
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 sync.RWMutex // 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 GetVirtRouterByPath ¶ added in v1.0.0
func GetVirtRouterByPath(path string) (*VirtRouter, bool)
根据path获取虚拟路由节点
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) GetMiddlewareConfig ¶ added in v1.0.0
func (vr *VirtRouter) GetMiddlewareConfig(name string) (*MiddlewareConfig, bool)
获取虚拟路由节点的中间件
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( "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("ini", "config.conf") cnf APIS: cnf.Set(key, val string) error cnf.String(key string) string cnf.Strings(key string) []string cnf.Int(key string) (int, error) cnf.Int64(key string) (int64, error) cnf.Bool(key string) (bool, error) cnf.Float(key string) (float64, error) cnf.DefaultString(key string, defaultVal string) string cnf.DefaultStrings(key string, defaultVal []string) []string cnf.DefaultInt(key string, defaultVal int) int cnf.DefaultInt64(key string, defaultVal int64) int64 cnf.DefaultBool(key string, defaultVal bool) bool cnf.DefaultFloat(key string, defaultVal float64) float64 cnf.DIY(key string) (interface{}, error) cnf.GetSection(section string) (map[string]string, error) cnf.SaveConfigFile(filename string) error more docs http://beego.me/docs/module/config.md
|
Package config is used to parse config Usage: import( "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("ini", "config.conf") cnf APIS: cnf.Set(key, val string) error cnf.String(key string) string cnf.Strings(key string) []string cnf.Int(key string) (int, error) cnf.Int64(key string) (int64, error) cnf.Bool(key string) (bool, error) cnf.Float(key string) (float64, error) cnf.DefaultString(key string, defaultVal string) string cnf.DefaultStrings(key string, defaultVal []string) []string cnf.DefaultInt(key string, defaultVal int) int cnf.DefaultInt64(key string, defaultVal int64) int64 cnf.DefaultBool(key string, defaultVal bool) bool cnf.DefaultFloat(key string, defaultVal float64) float64 cnf.DIY(key string) (interface{}, error) cnf.GetSection(section string) (map[string]string, error) cnf.SaveConfigFile(filename string) error more docs http://beego.me/docs/module/config.md |
xml
Package xml for config provider depend on github.com/beego/x2j go install github.com/beego/x2j Usage: import( _ "github.com/henrylee2cn/lessgo/config/xml" "github.com/henrylee2cn/lessgo/config" ) cnf, err := config.NewConfig("xml", "config.xml") more docs http://beego.me/docs/module/config.md
|
Package xml for config provider depend on github.com/beego/x2j go install github.com/beego/x2j Usage: import( _ "github.com/henrylee2cn/lessgo/config/xml" "github.com/henrylee2cn/lessgo/config" ) cnf, err := config.NewConfig("xml", "config.xml") more docs http://beego.me/docs/module/config.md |
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 depend on github.com/beego/goyaml2 go install github.com/beego/goyaml2 Usage: import( _ "github.com/henrylee2cn/lessgo/config/yaml" "github.com/henrylee2cn/lessgo/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.md
|
Package yaml for config provider depend on github.com/beego/goyaml2 go install github.com/beego/goyaml2 Usage: import( _ "github.com/henrylee2cn/lessgo/config/yaml" "github.com/henrylee2cn/lessgo/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.md |
Package logs provide a general log interface Usage: import "github.com/astaxie/beego/logs" log := NewLogger(10000) log.AddAdapter("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://beego.me/docs/module/logs.md
|
Package logs provide a general log interface Usage: import "github.com/astaxie/beego/logs" log := NewLogger(10000) log.AddAdapter("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://beego.me/docs/module/logs.md |
Blackfriday markdown processor.
|
Blackfriday markdown processor. |
A Django-syntax like template-engine Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2 Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/ Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/ Make sure to read README.md in the repository as well.
|
A Django-syntax like template-engine Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2 Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/ Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/ Make sure to read README.md in the repository as well. |
Package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
Package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
couchbase
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/henrylee2cn/lessgo/session/couchbase" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/henrylee2cn/lessgo/session/couchbase" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
ledis
Package ledis provide session Provider
|
Package ledis provide session Provider |
memcache
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/henrylee2cn/lessgo/session/memcache" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/henrylee2cn/lessgo/session/memcache" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
mysql
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/henrylee2cn/lessgo/session/mysql" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/henrylee2cn/lessgo/session/mysql" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
postgres
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/henrylee2cn/lessgo/session/postgresql" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/henrylee2cn/lessgo/session/postgresql" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
redis
Package redis for session provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/henrylee2cn/lessgo/session/redis" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
Package redis for session provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/henrylee2cn/lessgo/session/redis" "github.com/henrylee2cn/lessgo/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
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. |