Documentation ¶
Overview ¶
Package Faygo is a fast and concise Go Web framework that can be used to develop high-performance web app(especially API) with fewer codes; Just define a struct Handler, Faygo will automatically bind/verify the request parameters and generate the online API doc.
Copyright 2016 HenryLee. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
A trivial example is:
package main import ( // "mime/multipart" "time" "github.com/henrylee2cn/faygo" ) type Index struct { Id int `param:"<in:path> <required> <desc:ID> <range: 0:10>"` Title string `param:"<in:query> <nonzero>"` Paragraph []string `param:"<in:query> <name:p> <len: 1:10> <regexp: ^[\\w]*$>"` Cookie string `param:"<in:cookie> <name:faygoID>"` // Picture *multipart.FileHeader `param:"<in:formData> <name:pic> <maxmb:30>"` } func (i *Index) Serve(ctx *faygo.Context) error { if ctx.CookieParam("faygoID") == "" { ctx.SetCookie("faygoID", time.Now().String()) } return ctx.JSON(200, i) } func main() { app := faygo.New("myapp", "0.1") // Register the route in a chain style app.GET("/index/:id", new(Index)) // Register the route in a tree style // app.Route( // app.NewGET("/index/:id", new(Index)), // ) // Start the service faygo.Run() }
run result:
http GET: http://localhost:8080/index/1?title=test&p=abc&p=xyz response: { "Id": 1, "Title": "test", "Paragraph": [ "abc", "xyz" ], "Cookie": "2016-11-13 01:14:40.9038005 +0800 CST" }
StructHandler tag value description:
tag | key | required | value | desc ------|----------|----------|---------------|---------------------------------- param | in | only one | path | (position of param) if `required` is unsetted, auto set it. e.g. url: "http://www.abc.com/a/{path}" param | in | only one | query | (position of param) e.g. url: "http://www.abc.com/a?b={query}" param | in | only one | formData | (position of param) e.g. "request body: a=123&b={formData}" param | in | only one | body | (position of param) request body can be any content param | in | only one | header | (position of param) request header info param | in | only one | cookie | (position of param) request cookie info, support: `*http.Cookie`,`http.Cookie`,`string`,`[]byte` param | name | no | (e.g.`id`) | specify request param`s name param | required | no | | request param is required param | desc | no | (e.g.`id`) | request param description param | len | no | (e.g.`3:6` `3`) | length range of param's value param | range | no | (e.g.`0:10`) | numerical range of param's value param | nonzero | no | | param`s value can not be zero param | maxmb | no | (e.g.`32`) | when request Content-Type is multipart/form-data, the max memory for body.(multi-param, whichever is greater) param | regexp | no | (e.g.`^\\w+$`) | verify the value of the param with a regular expression(param value can not be null) param | err | no |(e.g.`incorrect password format`)| the custom error for binding or validating NOTES: 1. the binding object must be a struct pointer 2. in addition to `*multipart.FileHeader`, the binding struct's field can not be a pointer 3. `regexp` or `param` tag is only usable when `param:"type(xxx)"` is exist 4. if the `param` tag is not exist, anonymous field will be parsed 5. when the param's position(`in`) is `formData` and the field's type is `*multipart.FileHeader`, `multipart.FileHeader`, `[]*multipart.FileHeader` or `[]multipart.FileHeader`, the param receives file uploaded 6. if param's position(`in`) is `cookie`, field's type must be `*http.Cookie` or `http.Cookie` 7. param tags `in(formData)` and `in(body)` can not exist at the same time 8. there should not be more than one `in(body)` param tag
List of supported param value types:
base | slice | special --------|------------|------------------------------------------------------- string | []string | [][]byte byte | []byte | [][]uint8 uint8 | []uint8 | *multipart.FileHeader (only for `formData` param) bool | []bool | []*multipart.FileHeader (only for `formData` param) int | []int | *http.Cookie (only for `net/http`'s `cookie` param) int8 | []int8 | http.Cookie (only for `net/http`'s `cookie` param) int16 | []int16 | struct (struct type only for `body` param or as an anonymous field to extend params) int32 | []int32 | int64 | []int64 | uint8 | []uint8 | uint16 | []uint16 | uint32 | []uint32 | uint64 | []uint64 | float32 | []float32 | float64 | []float64 |
Index ¶
- Constants
- Variables
- func CleanToURL(p string) string
- func CloseLog()
- func ConfigDir() string
- func ContentTypeByExtension(ext string) string
- func Critical(args ...interface{})
- func Criticalf(format string, args ...interface{})
- func Debug(args ...interface{})
- func Debugf(format string, args ...interface{})
- func DecodeBody(dest reflect.Value, body []byte) error
- func Error(args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(format string, args ...interface{})
- func HandleBinderror(ctx *Context, err error)
- func HandleError(ctx *Context, errStr string, status int)
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func IsHandlerWithoutPath(handler Handler, noDefaultParams bool) bool
- func JoinStatic(shortFilename string) string
- func LogDir() string
- func MapParamName(fieldName string) (paramName string)
- func NewLog() *logging.Logger
- func Notice(args ...interface{})
- func Noticef(format string, args ...interface{})
- func Panic(args ...interface{})
- func Panicf(format string, args ...interface{})
- func Print(args ...interface{})
- func Printf(format string, args ...interface{})
- func Reboot(timeout ...time.Duration)
- func RemoveUseless()
- func RenderVar(name string, v interface{})
- func Run()
- func Running(name string, version ...string) bool
- func SetBinderrorFunc(binderrorFunc BinderrorFunc)
- func SetBodydecoder(bodydecoder apiware.Bodydecoder)
- func SetErrorFunc(errorFunc ErrorFunc)
- func SetParamNameMapper(paramNameMapper apiware.ParamNameMapper)
- func SetShutdown(timeout time.Duration, preCloseFunc, postCloseFunc func() error)
- func SetStatic(dir string, nocompress bool, nocache bool, handlers ...Handler)
- func SetUpload(dir string, nocompress bool, nocache bool, handlers ...Handler)
- func Shutdown(timeout ...time.Duration)
- func StaticDir() string
- func SyncINI(structPtr interface{}, f func(onecUpdateFunc func() error) error, ...) error
- func ToAPIHandler(handler Handler, noDefaultParams bool) (*apiHandler, error)
- func UploadDir() string
- func Warning(args ...interface{})
- func Warningf(format string, args ...interface{})
- func WritePid(pidFilename string) error
- type APIDoc
- type APIHandler
- type APIdocConfig
- type BinderrorFunc
- type Bodydecoder
- type CacheConfig
- type CacheFile
- type Config
- type Context
- func (ctx *Context) AcceptHTML() bool
- func (ctx *Context) AcceptJSON() bool
- func (ctx *Context) AcceptXML() bool
- func (ctx *Context) BindBizParam(dest interface{}, key string) error
- func (ctx *Context) BindForm(structObject interface{}) error
- func (ctx *Context) BindJSON(jsonObject interface{}) error
- func (ctx *Context) BindXML(xmlObject interface{}) error
- func (ctx *Context) BizParam(key string) string
- func (ctx *Context) Bytes(status int, contentType string, content []byte) error
- func (ctx *Context) Committed() bool
- func (ctx *Context) CookieParam(key string) string
- func (ctx *Context) Data(key interface{}) interface{}
- func (ctx *Context) DataAll() map[interface{}]interface{}
- func (ctx *Context) Del(key interface{})
- func (ctx *Context) DelSession(key interface{})
- func (ctx *Context) DestroySession()
- func (ctx *Context) Domain() string
- func (ctx *Context) Error(status int, errStr string)
- func (ctx *Context) File(localFilename string, showFilename ...string)
- func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (ctx *Context) FormParam(key string) string
- func (ctx *Context) FormParamAll() url.Values
- func (ctx *Context) FormParams(key string) []string
- func (ctx *Context) GetSession(key interface{}) interface{}
- func (ctx *Context) HTML(status int, html string) error
- func (ctx *Context) HasData(key interface{}) bool
- func (ctx *Context) HasFormFile(key string) bool
- func (ctx *Context) HeaderParam(key string) string
- func (ctx *Context) HeaderParamAll() http.Header
- func (ctx *Context) Host() string
- func (ctx *Context) IP() string
- func (ctx *Context) Is(method string) bool
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) IsBreak() bool
- func (ctx *Context) IsCachable() bool
- func (ctx *Context) IsClientError() bool
- func (ctx *Context) IsDelete() bool
- func (ctx *Context) IsEmpty() bool
- func (ctx *Context) IsForbidden() bool
- func (ctx *Context) IsGet() bool
- func (ctx *Context) IsHead() bool
- func (ctx *Context) IsNotFound() bool
- func (ctx *Context) IsOk() bool
- func (ctx *Context) IsOptions() bool
- func (ctx *Context) IsPatch() bool
- func (ctx *Context) IsPost() bool
- func (ctx *Context) IsPut() bool
- func (ctx *Context) IsRedirect() bool
- func (ctx *Context) IsSecure() bool
- func (ctx *Context) IsServerError() bool
- func (ctx *Context) IsSuccessful() bool
- func (ctx *Context) IsUpload() bool
- func (ctx *Context) IsWebsocket() bool
- func (ctx *Context) JSON(status int, data interface{}, isIndent ...bool) error
- func (ctx *Context) JSONBlob(status int, b []byte) error
- func (ctx *Context) JSONMsg(status int, msgcode int, info interface{}, isIndent ...bool) error
- func (ctx *Context) JSONOrXML(status int, data interface{}, isIndent ...bool) error
- func (ctx *Context) JSONP(status int, callback string, data interface{}, isIndent ...bool) error
- func (ctx *Context) LimitedBodyBytes() []byte
- func (ctx *Context) Log() *logging.Logger
- func (ctx *Context) Method() string
- func (ctx *Context) ModifyPath(p string)
- func (ctx *Context) Next()
- func (ctx *Context) NoContent(status int)
- func (ctx *Context) Param(key string) string
- func (ctx *Context) ParseFormOrMulitForm(maxMemory int64) error
- func (ctx *Context) Path() string
- func (ctx *Context) PathParam(key string) string
- func (ctx *Context) PathParamAll() PathParams
- func (ctx *Context) Port() int
- func (ctx *Context) Protocol() string
- func (ctx *Context) Proxy() []string
- func (ctx *Context) QueryParam(key string) string
- func (ctx *Context) QueryParamAll() url.Values
- func (ctx *Context) QueryParams(key string) []string
- func (ctx *Context) RealIP() string
- func (ctx *Context) Redirect(status int, urlStr string) error
- func (ctx *Context) Referer() string
- func (ctx *Context) Render(status int, name string, data Map) error
- func (ctx *Context) ReverseProxy(targetUrlBase string, pathAppend bool) error
- func (ctx *Context) SaveFile(key string, cover bool, newfname ...string) (savedFileInfo SavedFileInfo, err error)
- func (ctx *Context) SaveFiles(key string, cover bool, newfname ...string) (savedFileInfos []SavedFileInfo, err error)
- func (ctx *Context) Scheme() string
- func (ctx *Context) SecureCookieParam(secret, key string) (string, bool)
- func (ctx *Context) SessionRegenerateID()
- func (ctx *Context) SetCookie(name string, value string, others ...interface{})
- func (ctx *Context) SetData(key, val interface{})
- func (ctx *Context) SetHeader(key, val string)
- func (ctx *Context) SetSecureCookie(secret, name, value string, others ...interface{})
- func (ctx *Context) SetSession(key interface{}, value interface{})
- func (ctx *Context) Site() string
- func (ctx *Context) Size() int64
- func (ctx *Context) Status() int
- func (ctx *Context) Stop()
- func (ctx *Context) Stopped() bool
- func (ctx *Context) String(status int, format string, s ...interface{}) error
- func (ctx *Context) URI() string
- func (ctx *Context) URL() *url.URL
- func (ctx *Context) UserAgent() string
- func (ctx *Context) XML(status int, data interface{}, isIndent ...bool) error
- func (ctx *Context) XMLBlob(status int, b []byte) error
- func (ctx *Context) XSRFFormHTML() string
- func (ctx *Context) XSRFToken(specifiedExpiration ...int) string
- type Doc
- type ErrorFunc
- type FileInfo
- type FileServerManager
- func (c *FileServerManager) FileServer(fs FileSystem) Handler
- func (c *FileServerManager) Get(name string) (http.File, error)
- func (c *FileServerManager) Open(name string, encoding string, nocache bool) (http.File, error)
- func (c *FileServerManager) OpenFS(ctx *Context, name string, fs FileSystem) (http.File, error)
- func (c *FileServerManager) ServeContent(ctx *Context, name string, modtime time.Time, content io.ReadSeeker)
- func (c *FileServerManager) ServeFile(ctx *Context, name string, nocompressAndNocache ...bool)
- func (c *FileServerManager) Set(name string, body []byte, fileInfo os.FileInfo, encoding string) (http.File, error)
- type FileSystem
- type Framework
- func (frame *Framework) CloseLog()
- func (frame *Framework) Config() Config
- func (frame *Framework) ConfigFilename() string
- func (frame *Framework) Filter(fn ...HandlerFunc) *Framework
- func (frame *Framework) Log() *logging.Logger
- func (frame *Framework) MuxAPIsForRouter() []*MuxAPI
- func (frame *Framework) Name() string
- func (frame *Framework) NameWithVersion() string
- func (frame *Framework) NewAPI(methodset Methodset, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewDELETE(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewGET(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewGroup(pattern string, children ...*MuxAPI) *MuxAPI
- func (frame *Framework) NewHEAD(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedAPI(name string, methodset Methodset, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedDELETE(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedGET(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedGroup(name string, pattern string, children ...*MuxAPI) *MuxAPI
- func (frame *Framework) NewNamedHEAD(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedOPTIONS(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedPATCH(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedPOST(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedPUT(name string, pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewNamedStatic(name, pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
- func (frame *Framework) NewNamedStaticFS(name, pattern string, fs FileSystem) *MuxAPI
- func (frame *Framework) NewOPTIONS(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewPATCH(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewPOST(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewPUT(pattern string, handlers ...Handler) *MuxAPI
- func (frame *Framework) NewStatic(pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
- func (frame *Framework) NewStaticFS(pattern string, fs FileSystem) *MuxAPI
- func (frame *Framework) Route(children ...*MuxAPI) *MuxAPI
- func (frame *Framework) Run()
- func (frame *Framework) Running() bool
- func (frame *Framework) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (frame *Framework) Version() string
- type GlobalConfig
- type GlobalVariables
- type GzipConfig
- type Handle
- type Handler
- type HandlerChain
- type HandlerFunc
- type HandlerWithBody
- type HandlerWithoutPath
- type JSONMsg
- type LogConfig
- type Map
- type Methodset
- type MuxAPI
- func (mux *MuxAPI) API(methodset Methodset, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) Children() []*MuxAPI
- func (mux *MuxAPI) DELETE(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) Family() []*MuxAPI
- func (mux *MuxAPI) GET(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) Group(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) HEAD(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) HandlerProgeny() []*MuxAPI
- func (mux *MuxAPI) HasMethod(method string) bool
- func (mux *MuxAPI) IsGroup() bool
- func (mux *MuxAPI) Methods() []string
- func (mux *MuxAPI) Name() string
- func (mux *MuxAPI) NamedAPI(name string, methodset Methodset, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedDELETE(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedGET(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedGroup(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedHEAD(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedOPTIONS(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedPATCH(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedPOST(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedPUT(name string, pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) NamedStatic(name, pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
- func (mux *MuxAPI) NamedStaticFS(name, pattern string, fs FileSystem) *MuxAPI
- func (mux *MuxAPI) Notes() []Notes
- func (mux *MuxAPI) OPTIONS(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) PATCH(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) POST(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) PUT(pattern string, handlers ...Handler) *MuxAPI
- func (mux *MuxAPI) ParamInfos() []ParamInfo
- func (mux *MuxAPI) Parent() *MuxAPI
- func (mux *MuxAPI) Path() string
- func (mux *MuxAPI) Progeny() []*MuxAPI
- func (mux *MuxAPI) Static(pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
- func (mux *MuxAPI) StaticFS(pattern string, fs FileSystem) *MuxAPI
- func (mux *MuxAPI) Use(handlers ...Handler) *MuxAPI
- type MuxAPIs
- type Notes
- type ParamInfo
- type PathParam
- type PathParams
- type PresetStatic
- type Render
- type Response
- func (resp *Response) AddCookie(cookie *http.Cookie)
- func (resp *Response) CloseNotify() <-chan bool
- func (resp *Response) Committed() bool
- func (resp *Response) DelCookie()
- func (resp *Response) Flush()
- func (resp *Response) Header() http.Header
- func (resp *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (resp *Response) ReadFrom(src io.Reader) (int64, error)
- func (resp *Response) SetCookie(cookie *http.Cookie)
- func (resp *Response) Size() int64
- func (resp *Response) Status() int
- func (resp *Response) Write(b []byte) (int, error)
- func (resp *Response) WriteHeader(status int)
- type RouterConfig
- type SavedFileInfo
- type Server
- type SessionConfig
- type Tpl
- type XSRFConfig
Constants ¶
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderContentDescription = "Content-Description" HeaderContentTransferEncoding = "Content-Transfer-Encoding" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderReferer = "Referer" HeaderUserAgent = "User-Agent" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXForwardedFor = "X-Forwarded-For" HeaderXRealIP = "X-Real-IP" HeaderXRequestedWith = "X-Requested-With" 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" HeaderExpires = "Expires" HeaderCacheControl = "Cache-Control" HeaderPragma = "Pragma" // 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 ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + 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 ( // listenAndServe listens on the TCP network address and then // calls Serve to handle requests on incoming connections. // Accepted connections are configured to enable TCP keep-alives. // If srv.Addr is blank, ":http" is used. NETTYPE_HTTP = "http" // NETTYPE_HTTPS listens on the TCP network address and // then calls Serve to handle requests on incoming TLS connections. // Accepted connections are configured to enable TCP keep-alives. // // Filenames containing a certificate and matching private key for the // server must be provided if neither the Server's TLSConfig.Certificates // nor TLSConfig.GetCertificate are populated. If the certificate is // signed by a certificate authority, the certFile should be the // concatenation of the server's certificate, any intermediates, and // the CA's certificate. // // If server.Addr is blank, ":https" is used. NETTYPE_HTTPS = "https" // NETTYPE_LETSENCRYPT listens on a new Automatic TLS using letsencrypt.org service. // if you want to disable cache directory then simple give config `letsencrypt_dir` a value of empty string "". // // If server.Addr is blank, ":https" is used. NETTYPE_LETSENCRYPT = "letsencrypt" // NETTYPE_UNIX_LETSENCRYPT listens on a new Automatic TLS using letsencrypt.org Unix service. // if you want to disable cache directory then simple give config `letsencrypt_dir` a value of empty string "". // // If server.Addr is blank, ":https" is used. NETTYPE_UNIX_LETSENCRYPT = "unix_letsencrypt" // NETTYPE_UNIX_HTTP announces on the Unix domain socket addr and listens a Unix service. // // If server.Addr is blank, ":http" is used. NETTYPE_UNIX_HTTP = "unix_http" // NETTYPE_UNIX_HTTPS announces on the Unix domain socket addr and listens a secure Unix service. // // If server.Addr is blank, ":https" is used. NETTYPE_UNIX_HTTPS = "unix_https" )
network types
const FilepathKey = "filepath"
FilepathKey path key for static router pattern.
const ( // RUNMODE_DEV = "dev" // RUNMODE_PROD = "prod" MB = 1 << 20 // 1MB )
some default config
const MinShutdownTimeout = 5 * time.Second
MinShutdownTimeout the default time-out period for the services shutdown.
const ( // TAG_PARAM param tag TAG_PARAM = apiware.TAG_PARAM )
const (
// VERSION is faygo web framework's version
VERSION = "1.2.0"
)
Variables ¶
var ( ErrNotStructPtr = errors.New("handler must be a structure type or a structure pointer type") ErrNoParamHandler = errors.New("handler does not define any parameter tags") )
common errors
var BytesToString = goutil.BytesToString
BytesToString convert []byte type to string type.
func BytesToString(b []byte) string
var CamelString = goutil.CamelString
CamelString converts the accepted string to a camel string (xx_yy to XxYy)
func CamelString(s string) string
var FileExists = goutil.FileExists
FileExists reports whether the named file or directory exists.
func FileExists(name string) bool
var GrepFile = goutil.GrepFile
GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read
func GrepFile(patten string, filename string) (lines []string, err error)
var JsQueryEscape = goutil.JsQueryEscape
JsQueryEscape escapes the string in javascript standard so it can be safely placed inside a URL query.
func JsQueryEscape(s string) string
var JsQueryUnescape = goutil.JsQueryUnescape
JsQueryUnescape does the inverse transformation of JsQueryEscape, converting %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if any % is not followed by two hexadecimal digits.
func JsQueryUnescape(s string) (string, error)
var ObjectName = goutil.ObjectName
ObjectName gets the type name of the object
func ObjectName(i interface{}) string
var RESTfulMethodList = []string{
"CONNECT",
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT",
"TRACE",
}
RESTfulMethodList is the list of all RESTful methods
var RandomString = goutil.URLRandomString
RandomString returns a URL-safe, base64 encoded securely generated random string. It will panic if the system's secure random number generator fails to function correctly. The length n must be an integer multiple of 4, otherwise the last character will be padded with `=`.
func RandomString(n int) string
var RelPath = goutil.RelPath
RelPath gets relative path.
func RelPath() string
var SearchFile = goutil.SearchFile
SearchFile Search a file in paths. this is often used in search config file in /etc ~/
func SearchFile(filename string, paths ...string) (fullpath string, err error)
var SelfChdir = goutil.SelfChdir
SelfChdir switch the working path to my own path.
func SelfChdir()
var SelfDir = goutil.SelfDir
SelfDir gets compiled executable file directory
func SelfDir() string
var SelfPath = goutil.SelfPath
SelfPath gets compiled executable file absolute path.
func SelfPath() string
var SnakeString = goutil.SnakeString
SnakeString converts the accepted string to a snake string (XxYy to xx_yy)
func SnakeString(s string) string
var StringToBytes = goutil.StringToBytes
StringToBytes convert string type to []byte type. NOTE: panic if modify the member value of the []byte.
func StringToBytes(s string) []byte
var WalkDirs = goutil.WalkDirs
WalkDirs traverses the directory, return to the relative path. You can specify the suffix.
func WalkDirs(targpath string, suffixes ...string) (dirlist []string)
Functions ¶
func CleanToURL ¶
CleanToURL 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 ConfigDir ¶ added in v1.3.0
func ConfigDir() string
ConfigDir returns the config files directory
func ContentTypeByExtension ¶
ContentTypeByExtension gets the content type from ext string. MIME type is given in mime package. It returns `application/octet-stream` incase MIME type is not found.
func Critical ¶
func Critical(args ...interface{})
Critical logs a message using CRITICAL as log level.
func Criticalf ¶
func Criticalf(format string, args ...interface{})
Criticalf logs a message using CRITICAL as log level.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs a message using DEBUG as log level.
func DecodeBody ¶
DecodeBody decodes params from request body.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs a message using ERROR as log level.
func Fatal ¶
func Fatal(args ...interface{})
Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1).
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf is equivalent to l.Critical followed by a call to os.Exit(1).
func HandleBinderror ¶
HandleBinderror calls the default parameter binding failure handler.
func HandleError ¶
HandleError calls the default error handler.
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs a message using INFO as log level.
func IsHandlerWithoutPath ¶
IsHandlerWithoutPath verifies that the Handler is an HandlerWithoutPath.
func JoinStatic ¶
JoinStatic adds the static directory prefix to the file name.
func MapParamName ¶
MapParamName maps the APIHander's parameter name from the structure field. When the APIHander's parameter name (struct tag) is unsetted, it is mapped from the structure field name by default. If `paramNameMapper` is nil, use snake style.
func Noticef ¶
func Noticef(format string, args ...interface{})
Noticef logs a message using NOTICE as log level.
func Panic ¶
func Panic(args ...interface{})
Panic is equivalent to l.Critical(fmt.Sprint()) followed by a call to panic().
func Panicf ¶
func Panicf(format string, args ...interface{})
Panicf is equivalent to l.Critical followed by a call to panic().
func Print ¶
func Print(args ...interface{})
Print logs a message using CRITICAL as log level, only with time prefix.
func Printf ¶
func Printf(format string, args ...interface{})
Printf logs a message using CRITICAL as log level, only with time prefix.
func RemoveUseless ¶
func RemoveUseless()
RemoveUseless when there's not frame instance, remove files: config, log, static and upload .
func RenderVar ¶
func RenderVar(name string, v interface{})
RenderVar sets the global template variable, function or pongo2.FilterFunction for pongo2 render.
func SetBinderrorFunc ¶
func SetBinderrorFunc(binderrorFunc BinderrorFunc)
SetBinderrorFunc sets the global default `BinderrorFunc` function.
func SetBodydecoder ¶
func SetBodydecoder(bodydecoder apiware.Bodydecoder)
SetBodydecoder sets the global default `Bodydecoder` function.
func SetErrorFunc ¶
func SetErrorFunc(errorFunc ErrorFunc)
SetErrorFunc sets the global default `ErrorFunc` function.
func SetParamNameMapper ¶
func SetParamNameMapper(paramNameMapper apiware.ParamNameMapper)
SetParamNameMapper sets the global default `ParamNameMapper` function.
func SetShutdown ¶
SetShutdown sets the function which is called after the services shutdown, and the time-out period for the services shutdown. If 0<=timeout<5s, automatically use 'MinShutdownTimeout'(5s). If timeout<0, indefinite period. 'preCloseFunc' is executed before closing services, but not guaranteed to be completed. 'postCloseFunc' is executed after services are closed, but not guaranteed to be completed.
func SetStatic ¶
SetStatic sets static folder path, such as `./staic/` with a slash `/` at the end. note: it should be called before Run()
func SetUpload ¶
SetUpload sets upload folder path such as `./upload/` with a slash `/` at the end. note: it should be called before Run()
func Shutdown ¶
Shutdown closes all the frame services gracefully. Parameter timeout is used to reset time-out period for the services shutdown.
func StaticDir ¶
func StaticDir() string
StaticDir returns static folder path with a slash at the end
func SyncINI ¶
func SyncINI(structPtr interface{}, f func(onecUpdateFunc func() error) error, filename ...string) error
SyncINI quickly create your own configuration files. Struct tags reference `https://github.com/go-ini/ini`
func ToAPIHandler ¶
ToAPIHandler tries converts it to an *apiHandler.
func UploadDir ¶
func UploadDir() string
UploadDir returns upload folder path with a slash at the end
Types ¶
type APIDoc ¶
type APIDoc interface {
Doc() Doc
}
APIDoc provides the API's note, result or parameters information.
type APIHandler ¶
APIHandler is the Faygo Handler interface, which is implemented by a struct with API descriptor information. It is an intelligent Handler of binding parameters.
type APIdocConfig ¶
type APIdocConfig struct { Enable bool `ini:"enable" comment:"Whether enabled or not"` Path string `ini:"path" comment:"The URL path"` NoLimit bool `ini:"nolimit" comment:"If true, access is not restricted"` RealIP bool `ini:"real_ip" comment:"if true, means verifying the real IP of the visitor"` Whitelist []string `` /* 166-byte string literal not displayed */ Desc string `ini:"desc" comment:"Description of the application"` Email string `ini:"email" comment:"Technician's Email"` TermsURL string `ini:"terms_url" comment:"Terms of service"` License string `ini:"license" comment:"The license used by the API"` LicenseURL string `ini:"license_url" comment:"The URL of the protocol content page"` }
APIdocConfig is the config about API doc
type BinderrorFunc ¶
BinderrorFunc is called when binding or validation apiHandler parameters are wrong.
type Bodydecoder ¶
Bodydecoder is an interface to customize decoding operation
type CacheConfig ¶
type CacheConfig struct { // Whether to enable caching static files Enable bool `ini:"enable" comment:"Whether enabled or not"` // Max size by MB for file cache. // The cache size will be set to 512KB at minimum. // If the size is set relatively large, you should call // `debug.SetGCPercent()`, set it to a much smaller value // to limit the memory consumption and GC pause time. SizeMB int64 `ini:"size_mb" comment:"Max size by MB for file cache, the cache size will be set to 512KB at minimum."` // expire in xxx seconds for file cache. // ExpireSecond <= 0 (second) means no expire, but it can be evicted when cache is full. ExpireSecond int `ini:"expire_second" comment:"Maximum duration for caching"` }
CacheConfig is the config about cache
type Config ¶
type Config struct { // RunMode string `ini:"run_mode" comment:"run mode: dev|prod"` NetTypes []string `ini:"net_types" delim:"|" comment:"List of network type: http|https|unix_http|unix_https|letsencrypt|unix_letsencrypt"` Addrs []string `ini:"addrs" delim:"|" comment:"List of multiple listening addresses"` TLSCertFile string `ini:"tls_certfile" comment:"TLS certificate file path"` TLSKeyFile string `ini:"tls_keyfile" comment:"TLS key file path"` LetsencryptDir string `ini:"letsencrypt_dir" comment:"Let's Encrypt TLS certificate cache directory"` UNIXFileMode string `ini:"unix_filemode" comment:"File permissions for UNIX listener, requires octal number"` HttpRedirectHttps bool `ini:"http_redirect_https" comment:"Redirect from 'http://hostname:port1' to 'https://hostname:port2'"` // Maximum duration for reading the full request (including body). // // This also limits the maximum duration for idle keep-alive // connections. // // By default request read timeout is unlimited. ReadTimeout time.Duration `ini:"read_timeout" comment:"Maximum duration for reading the full request (including body); ns|µs|ms|s|m|h"` // Maximum duration for writing the full response (including body). // // By default response write timeout is unlimited. WriteTimeout time.Duration `ini:"write_timeout" comment:"Maximum duration for writing the full response (including body); ns|µs|ms|s|m|h"` MultipartMaxMemoryMB int64 `ini:"multipart_maxmemory_mb" comment:"Maximum size of memory that can be used when receiving uploaded files"` Router RouterConfig `ini:"router" comment:"Routing config section"` XSRF XSRFConfig `ini:"xsrf" comment:"XSRF security section"` Session SessionConfig `ini:"session" comment:"Session section"` SlowResponseThreshold time.Duration `` /* 145-byte string literal not displayed */ PrintBody bool `ini:"print_body" comment:"Form requests are printed in JSON format, but other types are printed as-is"` APIdoc APIdocConfig `ini:"apidoc" comment:"API documentation section"` // contains filtered or unexported fields }
Config is the config information for each web instance
func NewDefaultConfig ¶
func NewDefaultConfig() *Config
NewDefaultConfig creates a new default framework config.
type Context ¶
type Context struct { R *http.Request // the *http.Request W *Response // the *Response cooked by the http.ResponseWriter // contains filtered or unexported fields }
Context is resetting every time a ruest is coming to the server it is not good practice to use this object in goroutines, for these cases use the .Clone()
func (*Context) AcceptHTML ¶
AcceptHTML Checks if request accepts html response
func (*Context) AcceptJSON ¶
AcceptJSON Checks if request accepts json response
func (*Context) BindBizParam ¶
BindBizParam data from ctx.BizParam(key) to dest
like /?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=abc var id int ctx.BindBizParam(&id, "id") id ==123 var isok bool ctx.BindBizParam(&isok, "isok") isok ==true var ft float64 ctx.BindBizParam(&ft, "ft") ft ==1.2 ol := make([]int, 0, 2) ctx.BindBizParam(&ol, "ol") ol ==[1 2] ul := make([]string, 0, 2) ctx.BindBizParam(&ul, "ul") ul ==[str array] user struct{Name} ctx.BindBizParam(&user, "user") user == {Name:"abc"}
func (*Context) BizParam ¶
BizParam returns the first value for the kinds of business parameters. priority: path parameters > POST and PUT body parameters > URL query string values.
BizParam calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, BizParam returns the empty string. To access multiple values of the same key, call ParseForm and then inspect Request.Form directly.
func (*Context) CookieParam ¶
CookieParam returns request cookie item string by a given key. if non-existed, return empty string.
func (*Context) Data ¶
func (ctx *Context) Data(key interface{}) interface{}
Data returns the stored data in this context.
func (*Context) DataAll ¶
func (ctx *Context) DataAll() map[interface{}]interface{}
DataAll return the implicit data in the context
func (*Context) DelSession ¶
func (ctx *Context) DelSession(key interface{})
DelSession removes value from session.
func (*Context) DestroySession ¶
func (ctx *Context) DestroySession()
DestroySession cleans session data and session cookie.
func (*Context) File ¶
File forces response for download file. it prepares the download response header automatically.
func (*Context) FormFile ¶
FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.
func (*Context) FormParam ¶
FormParam returns the first value for the named component of the POST or PUT ruest body. URL query parameters and path parameters are ignored. FormParam calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, FormParam returns the empty string.
func (*Context) FormParamAll ¶
FormParamAll returns the parsed form data from POST, PATCH, or PUT body parameters.
func (*Context) FormParams ¶
FormParams returns the form field value with "[]string" for the provided key.
func (*Context) GetSession ¶
func (ctx *Context) GetSession(key interface{}) interface{}
GetSession gets value from session.
func (*Context) HasFormFile ¶
HasFormFile returns if the file header for the provided form key is exist.
func (*Context) HeaderParam ¶
HeaderParam gets the first header value associated with the given key. If there are no values associated with the key, HeaderParam returns the empty string.
func (*Context) HeaderParamAll ¶
HeaderParamAll returns the whole ruest header.
func (*Context) Host ¶
Host returns a host:port string for this request, such as "www.example.com" or "www.example.com:8080".
func (*Context) IsCachable ¶
IsCachable returns boolean of this request is cached. HTTP 304 means cached.
func (*Context) IsClientError ¶
IsClientError returns boolean of this request client sends error data. HTTP 4xx means forbidden.
func (*Context) IsEmpty ¶
IsEmpty returns boolean of this request is empty. HTTP 201,204 and 304 means empty.
func (*Context) IsForbidden ¶
IsForbidden returns boolean of this request is forbidden. HTTP 403 means forbidden.
func (*Context) IsNotFound ¶
IsNotFound returns boolean of this request is not found. HTTP 404 means forbidden.
func (*Context) IsRedirect ¶
IsRedirect returns boolean of this request is redirection header. HTTP 301,302,307 means redirection.
func (*Context) IsServerError ¶
IsServerError returns boolean of this server handler errors. HTTP 5xx means server internal error.
func (*Context) IsSuccessful ¶
IsSuccessful returns boolean of this request runs successfully. HTTP 2xx means ok.
func (*Context) IsUpload ¶
IsUpload returns boolean of whether file uploads in this request or not..
func (*Context) IsWebsocket ¶
IsWebsocket returns boolean of this request is in webSocket.
func (*Context) JSONOrXML ¶
JSONOrXML serve Xml OR Json, depending on the value of the Accept header
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) LimitedBodyBytes ¶
LimitedBodyBytes returns the raw request body data as bytes. Note:
1.limited by maximum length; 2.if frame.config.PrintBody==false and ctx.R.Body is readed, returns nil; 3.if ctx.IsUpload()==true and ctx.R.Body is readed, returns nil.
func (*Context) ModifyPath ¶
ModifyPath modifies the access path for the request.
func (*Context) Next ¶
func (ctx *Context) Next()
Next calls all the next handler from the middleware stack, it used inside a middleware. Notes: Non-concurrent security.
func (*Context) Param ¶
Param returns the first value for the kinds of parameters. priority: path parameters > POST and PUT body parameters > URL query string values > header > cookie.Value.
Param calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, Param returns the empty string. To access multiple values of the same key, call ParseForm and then inspect Request.Form directly.
func (*Context) ParseFormOrMulitForm ¶
ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type
func (*Context) PathParamAll ¶
func (ctx *Context) PathParamAll() PathParams
PathParamAll returns whole path parameters.
func (*Context) QueryParam ¶
QueryParam gets the first query value associated with the given key. If there are no values associated with the key, QueryParam returns the empty string.
func (*Context) QueryParamAll ¶
QueryParamAll returns all query params.
func (*Context) QueryParams ¶
QueryParams returns the query param with "[]string".
func (*Context) RealIP ¶
RealIP returns request client ip. if in proxy, return first proxy id. if error, return 127.0.0.1.
func (*Context) Redirect ¶
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
The provided status code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
func (*Context) Render ¶
Render renders a template with data and sends a text/html response with status code.
func (*Context) ReverseProxy ¶
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 ruest was for "/dir", the target ruest will be for /base/dir.
func (*Context) SaveFile ¶
func (ctx *Context) SaveFile(key string, cover bool, newfname ...string) (savedFileInfo SavedFileInfo, err error)
SaveFile saves the uploaded file to global.UploadDir(), character "?" indicates that the original file name. for example newfname="a/?" -> global.UploadDir()/a/fname.
func (*Context) SaveFiles ¶
func (ctx *Context) SaveFiles(key string, cover bool, newfname ...string) (savedFileInfos []SavedFileInfo, err error)
SaveFiles saves the uploaded files to global.UploadDir(), it's similar to SaveFile, but for saving multiple files.
func (*Context) SecureCookieParam ¶
SecureCookieParam Get secure cookie from request by a given key.
func (*Context) SessionRegenerateID ¶
func (ctx *Context) SessionRegenerateID()
SessionRegenerateID regenerates session id for this session. the session data have no changes.
func (*Context) SetCookie ¶
SetCookie sets cookie value via given key. others are ordered as cookie's max age time, path, domain, secure and httponly.
func (*Context) SetData ¶
func (ctx *Context) SetData(key, val interface{})
SetData stores data with given key in this context. This data are only available in this context.
func (*Context) SetSecureCookie ¶
SetSecureCookie Set Secure cookie for response.
func (*Context) SetSession ¶
func (ctx *Context) SetSession(key interface{}, value interface{})
SetSession puts value into session.
func (*Context) Stop ¶
func (ctx *Context) Stop()
Stop just sets the .pos to 32766 in order to not move to the next handlers(if any)
func (*Context) XSRFFormHTML ¶
XSRFFormHTML writes an input field contains xsrf token value.
type Doc ¶
type Doc struct { Note string `json:"note" xml:"note"` Return interface{} `json:"return,omitempty" xml:"return,omitempty"` // MoreParams extra added parameters definition MoreParams []ParamInfo `json:"more_params,omitempty" xml:"more_params,omitempty"` }
Doc api information
type ErrorFunc ¶
ErrorFunc replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to ctx. The error message should be plain text.
type FileInfo ¶
type FileInfo struct {
// contains filtered or unexported fields
}
FileInfo implements os.FileInfo
type FileServerManager ¶
type FileServerManager struct {
// contains filtered or unexported fields
}
FileServerManager is file cache system manager
func (*FileServerManager) FileServer ¶
func (c *FileServerManager) FileServer(fs FileSystem) Handler
FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at fs.
To use the operating system's file system implementation, use http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".
func (*FileServerManager) Get ¶
func (c *FileServerManager) Get(name string) (http.File, error)
Get gets file from cache.
func (*FileServerManager) Open ¶
Open gets or stores the file with compression and caching options. If the name is larger than 65535 or body is larger than 1/1024 of the cache size, the entry will not be written to the cache.
func (*FileServerManager) OpenFS ¶
func (c *FileServerManager) OpenFS(ctx *Context, name string, fs FileSystem) (http.File, error)
OpenFS gets or stores the cache file. If the name is larger than 65535 or body is larger than 1/1024 of the cache size, the entry will not be written to the cache.
func (*FileServerManager) ServeContent ¶
func (c *FileServerManager) ServeContent(ctx *Context, name string, modtime time.Time, content io.ReadSeeker)
ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Modified-Since requests.
If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.
If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.
The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.
If the caller has set ctx's ETag header, ServeContent uses it to handle requests using If-Range and If-None-Match.
Note that *os.File implements the io.ReadSeeker interface.
func (*FileServerManager) ServeFile ¶
func (c *FileServerManager) ServeFile(ctx *Context, name string, nocompressAndNocache ...bool)
ServeFile replies to the request with the contents of the named file or directory.
If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile. As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element.
As a special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.
type FileSystem ¶
type FileSystem interface { http.FileSystem Nocompress() bool // not allowed compress Nocache() bool // not allowed cache }
FileSystem is a file system with compression and caching options
func DirFS ¶
func DirFS(root string, nocompressAndNocache ...bool) FileSystem
DirFS creates a file system with compression and caching options, similar to http.Dir
func FS ¶
func FS(fs http.FileSystem, nocompressAndNocache ...bool) FileSystem
FS creates a file system with compression and caching options
func MarkdownFS ¶
func MarkdownFS(root string, nocompressAndNocache ...bool) FileSystem
MarkdownFS creates a markdown file system.
type Framework ¶
type Framework struct { // root muxAPI node *MuxAPI // contains filtered or unexported fields }
Framework is the faygo web framework.
func AllFrames ¶
func AllFrames() []*Framework
AllFrames returns the list of applications that have been created.
func NewWithConfig ¶
NewWithConfig uses the faygo web framework to create a new application.
func (*Framework) ConfigFilename ¶
ConfigFilename returns the framework's config file name.
func (*Framework) Filter ¶
func (frame *Framework) Filter(fn ...HandlerFunc) *Framework
Filter operations that are called before the route is matched.
func (*Framework) MuxAPIsForRouter ¶
MuxAPIsForRouter get an ordered list of nodes used to register router.
func (*Framework) NameWithVersion ¶
NameWithVersion returns the name with version
func (*Framework) NewDELETE ¶
NewDELETE is a shortcut for frame.NewAPI("DELETE", pattern, handlers...)
func (*Framework) NewNamedAPI ¶
func (frame *Framework) NewNamedAPI(name string, methodset Methodset, pattern string, handlers ...Handler) *MuxAPI
NewNamedAPI creates an isolated muxAPI node with the name.
func (*Framework) NewNamedDELETE ¶
NewNamedDELETE is a shortcut for frame.NewNamedAPI(name, "DELETE", pattern, handlers...)
func (*Framework) NewNamedGET ¶
NewNamedGET is a shortcut for frame.NewNamedAPI(name, "GET", pattern, handlers...)
func (*Framework) NewNamedGroup ¶
NewNamedGroup creates an isolated grouping muxAPI node with the name.
func (*Framework) NewNamedHEAD ¶
NewNamedHEAD is a shortcut for frame.NewNamedAPI(name, "HEAD", pattern, handlers...)
func (*Framework) NewNamedOPTIONS ¶
NewNamedOPTIONS is a shortcut for frame.NewNamedAPI(name, "OPTIONS", pattern, handlers...)
func (*Framework) NewNamedPATCH ¶
NewNamedPATCH is a shortcut for frame.NewNamedAPI(name, "PATCH", pattern, handlers...)
func (*Framework) NewNamedPOST ¶
NewNamedPOST is a shortcut for frame.NewNamedAPI(name, "POST", pattern, handlers...)
func (*Framework) NewNamedPUT ¶
NewNamedPUT is a shortcut for frame.NewNamedAPI(name, "PUT", pattern, handlers...)
func (*Framework) NewNamedStatic ¶
func (frame *Framework) NewNamedStatic(name, pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
NewNamedStatic creates an isolated static muxAPI node with the name.
func (*Framework) NewNamedStaticFS ¶
func (frame *Framework) NewNamedStaticFS(name, pattern string, fs FileSystem) *MuxAPI
NewNamedStaticFS creates an isolated static muxAPI node with the name.
func (*Framework) NewOPTIONS ¶
NewOPTIONS is a shortcut for frame.NewAPI("OPTIONS", pattern, handlers...)
func (*Framework) NewStatic ¶
func (frame *Framework) NewStatic(pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
NewStatic creates an isolated static muxAPI node.
func (*Framework) NewStaticFS ¶
func (frame *Framework) NewStaticFS(pattern string, fs FileSystem) *MuxAPI
NewStaticFS creates an isolated static muxAPI node.
func (*Framework) Route ¶
Route append middlewares of function type to root muxAPI. Used to register router in tree style.
type GlobalConfig ¶
type GlobalConfig struct { Cache CacheConfig `ini:"cache" comment:"Cache section"` Gzip GzipConfig `ini:"gzip" comment:"Gzip section"` Log LogConfig `ini:"log" comment:"Log section"` // contains filtered or unexported fields }
GlobalConfig is global config
type GlobalVariables ¶
type GlobalVariables struct {
// contains filtered or unexported fields
}
GlobalVariables defines the global frames, configuration, function and so on.
type GzipConfig ¶
type GzipConfig struct { // if EnableGzip, compress response content. Enable bool `ini:"enable" comment:"Whether enabled or not"` //Content will only be compressed if content length is either unknown or greater than gzipMinLength. //Default size==20B same as nginx MinLength int `ini:"min_length" comment:"The minimum length of content to be compressed"` //The compression level used for deflate compression. (0-9). //Non-file response Body's compression level is 0-9, but the files' always 9 CompressLevel int `ini:"compress_level" comment:"Non-file response Body's compression level is 0-9, but the files' always 9"` //List of HTTP methods to compress. If not set, only GET requests are compressed. Methods []string `ini:"methods" delim:"|" comment:"List of HTTP methods to compress. If not set, only GET requests are compressed."` }
GzipConfig is the config about gzip
type Handle ¶
type Handle func(*Context, PathParams)
Handle is a function that can be registered to a route to handle HTTP requests.
type HandlerChain ¶
type HandlerChain []Handler
HandlerChain is the chain of handlers for a request.
type HandlerFunc ¶
HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
func (HandlerFunc) Serve ¶
func (h HandlerFunc) Serve(ctx *Context) error
Serve implements the Handler, is like ServeHTTP but for Faygo.
type HandlerWithBody ¶
type HandlerWithBody interface { Handler Bodydecoder // Decode params from request body }
HandlerWithBody is the Faygo APIHandler interface but with DecodeBody method.
type HandlerWithoutPath ¶
type HandlerWithoutPath interface { Handler }
HandlerWithoutPath is handler without binding path parameter for middleware.
type JSONMsg ¶
type JSONMsg struct { Code int `json:"code" xml:"code"` // the status code of the business process (required) Info interface{} `json:"info,omitempty" xml:"info,omitempty"` // response's schema and example value (optional) }
JSONMsg is commonly used to return JSON format response.
type LogConfig ¶
type LogConfig struct { ConsoleEnable bool `ini:"console_enable" comment:"Whether enabled or not console logger"` ConsoleLevel string `ini:"console_level" comment:"Console logger level: critical|error|warning|notice|info|debug"` FileEnable bool `ini:"file_enable" comment:"Whether enabled or not file logger"` FileLevel string `ini:"file_level" comment:"File logger level: critical|error|warning|notice|info|debug"` AsyncLen int `ini:"async_len" comment:"The length of asynchronous buffer, 0 means synchronization"` }
LogConfig is the config about log
type Map ¶
type Map map[string]interface{}
Map is just a conversion for a map[string]interface{} should not be used inside Render when PongoEngine is used.
type MuxAPI ¶
type MuxAPI struct {
// contains filtered or unexported fields
}
MuxAPI the visible api for the serveMux, in order to prepare for routing.
func (*MuxAPI) API ¶
API adds a subordinate node to the current muxAPI grouping node. notes: handler cannot be nil.
func (*MuxAPI) Group ¶
Group adds a subordinate subgroup node to the current muxAPI grouping node. notes: handler cannot be nil.
func (*MuxAPI) HandlerProgeny ¶
HandlerProgeny returns an ordered list of subordinate nodes used to register router.
func (*MuxAPI) NamedAPI ¶
func (mux *MuxAPI) NamedAPI(name string, methodset Methodset, pattern string, handlers ...Handler) *MuxAPI
NamedAPI adds a subordinate node with the name to the current muxAPI grouping node. notes: handler cannot be nil.
func (*MuxAPI) NamedDELETE ¶
NamedDELETE is a shortcut for muxAPI.NamedAPI(name, "DELETE", pattern, handlers...)
func (*MuxAPI) NamedGET ¶
NamedGET is a shortcut for muxAPI.NamedAPI(name, "GET", pattern, handlers...)
func (*MuxAPI) NamedGroup ¶
NamedGroup adds a subordinate subgroup node with the name to the current muxAPI grouping node. notes: handler cannot be nil.
func (*MuxAPI) NamedHEAD ¶
NamedHEAD is a shortcut for muxAPI.NamedAPI(name, "HEAD", pattern, handlers...)
func (*MuxAPI) NamedOPTIONS ¶
NamedOPTIONS is a shortcut for muxAPI.NamedAPI(name, "OPTIONS", pattern, handlers...)
func (*MuxAPI) NamedPATCH ¶
NamedPATCH is a shortcut for muxAPI.NamedAPI(name, "PATCH", pattern, handlers...)
func (*MuxAPI) NamedPOST ¶
NamedPOST is a shortcut for muxAPI.NamedAPI(name, "POST", pattern, handlers...)
func (*MuxAPI) NamedPUT ¶
NamedPUT is a shortcut for muxAPI.NamedAPI(name, "PUT", pattern, handlers...)
func (*MuxAPI) NamedStatic ¶
func (mux *MuxAPI) NamedStatic(name, pattern string, root string, nocompressAndNocache ...bool) *MuxAPI
NamedStatic is similar to NamedStaticFS, but the second parameter is the local file path.
func (*MuxAPI) NamedStaticFS ¶
func (mux *MuxAPI) NamedStaticFS(name, pattern string, fs FileSystem) *MuxAPI
NamedStaticFS serves files from the given file system fs. The pattern must end with "/*filepath", files are then served from the local pattern /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:
frame.StaticFS("/src/*filepath", Dir("/var/www", true, true)
func (*MuxAPI) ParamInfos ¶
ParamInfos returns the paramInfos of muxAPI node.
type Notes ¶
type Notes struct { Note string `json:"note" xml:"note"` Return interface{} `json:"return,omitempty" xml:"return,omitempty"` }
Notes implementation notes of a response
type ParamInfo ¶
type ParamInfo struct { Name string // Parameter name In string // The position of the parameter Required bool // Is a required parameter Model interface{} // A parameter value that is used to infer a value type and as a default value Desc string // Description }
ParamInfo is the request parameter information
type PathParams ¶
type PathParams []PathParam
PathParams is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
func (PathParams) ByName ¶
func (ps PathParams) ByName(name string) string
ByName returns the value of the first PathParam which key matches the given name. If no matching PathParam is found, an empty string is returned.
type PresetStatic ¶
type PresetStatic struct {
// contains filtered or unexported fields
}
PresetStatic is the system default static file routing information
type Render ¶
Render is a custom faygo template renderer using pongo2.
func GetRender ¶
func GetRender() *Render
GetRender returns a custom faygo template renderer using pongo2.
func (*Render) RenderFromBytesWithName ¶
func (render *Render) RenderFromBytesWithName(filename string, fbytes []byte, data Map) ([]byte, error)
RenderFromBytesWithName should render the template to the io.Writer.
func (*Render) TemplateVar ¶
TemplateVar sets the global template variable or 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 (*Response) AddCookie ¶
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) 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) ReadFrom ¶
ReadFrom is here to optimize copying from an *os.File regular file to a *net.TCPConn with sendfile.
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.
type RouterConfig ¶
type RouterConfig 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 `ini:"redirect_trailing_slash" comment:"Automatic redirection (for example, '/foo/' -> '/foo')"` // 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 `ini:"redirect_fixed_path" comment:"Tries to fix the current request path, if no handle is registered for it"` // 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 `ini:"handle_method_not_allowed" comment:"Returns 405 if the requested method does not exist, otherwise returns 404"` // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool `ini:"handle_options" comment:"Automatic response OPTIONS request, you can set the default Handler in faygo"` NoDefaultParams bool `` /* 145-byte string literal not displayed */ DefaultUpload bool `ini:"default_upload" comment:"Automatically register the default router: /upload/*filepath"` DefaultStatic bool `ini:"default_static" comment:"Automatically register the default router: /static/*filepath"` }
RouterConfig is the config about router
type SavedFileInfo ¶
SavedFileInfo for SaveFiles()
type SessionConfig ¶
type SessionConfig struct { Enable bool `ini:"enable" comment:"Whether enabled or not"` Provider string `ini:"provider" comment:"Data storage"` Name string `ini:"name" comment:"The client stores the name of the cookie"` ProviderConfig string `ini:"provider_config" comment:"According to the different engine settings different config information"` CookieLifeSecond int `ini:"cookie_life_second" comment:"The default value is 0, which is the lifetime of the browser"` GcLifeSecond int64 `ini:"gc_life_second" comment:"The interval between triggering the GC"` MaxLifeSecond int64 `ini:"max_life_second" comment:"The session max lefetime"` AutoSetCookie bool `ini:"auto_setcookie" comment:"Automatically set on the session cookie value, the general default true"` Domain string `ini:"domain" comment:"The domain name that is allowed to access this cookie"` EnableSidInHttpHeader bool `ini:"enable_sid_in_header" comment:"Whether to write a session ID to the header"` NameInHttpHeader string `ini:"name_in_header" comment:"The name of the header when the session ID is written to the header"` EnableSidInUrlQuery bool `ini:"enable_sid_in_urlquery" comment:"Whether to write the session ID to the URL Query params"` }
SessionConfig is the config about session
type Tpl ¶
type Tpl struct {
// contains filtered or unexported fields
}
Tpl is template with modfied time.
type XSRFConfig ¶
type XSRFConfig struct { Enable bool `ini:"enable" comment:"Whether enabled or not"` Key string `ini:"key" comment:"Encryption key"` ExpireSecond int `ini:"expire_second" comment:"Expire of XSRF token"` }
XSRFConfig is the config about XSRF filter
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package apiware provides a tools which can bind the http/fasthttp request params to the structure and validate.
|
Package apiware provides a tools which can bind the http/fasthttp request params to the structure and validate. |
ext
|
|
barcode/codabar
Package codabar can create Codabar barcodes
|
Package codabar can create Codabar barcodes |
barcode/code128
Package code128 can create Code128 barcodes
|
Package code128 can create Code128 barcodes |
barcode/code39
Package code39 can create Code39 barcodes
|
Package code39 can create Code39 barcodes |
barcode/datamatrix
Package datamatrix can create Datamatrix barcodes
|
Package datamatrix can create Datamatrix barcodes |
barcode/ean
Package ean can create EAN 8 and EAN 13 barcodes.
|
Package ean can create EAN 8 and EAN 13 barcodes. |
barcode/qr
Package qr can be used to create QR barcodes.
|
Package qr can be used to create QR barcodes. |
barcode/twooffive
Package twooffive can create interleaved and standard "2 of 5" barcodes.
|
Package twooffive can create interleaved and standard "2 of 5" barcodes. |
barcode/utils
Package utils contain some utilities which are needed to create barcodes
|
Package utils contain some utilities which are needed to create barcodes |
cron
Package cron implements a cron spec parser and job runner.
|
Package cron implements a cron spec parser and job runner. |
db/directsql
* * desc : 参数校验函数 * author : 畅雨 * date : 2016.12.13 * desc : * history : 2018.06.15: - 默认参数增加直接设置值类型,DT_VALUE,格式{value} ,示例:{""},{0} 2017.05.28 - 增加主从表关联id的服务端处理。
|
* * desc : 参数校验函数 * author : 畅雨 * date : 2016.12.13 * desc : * history : 2018.06.15: - 默认参数增加直接设置值类型,DT_VALUE,格式{value} ,示例:{""},{0} 2017.05.28 - 增加主从表关联id的服务端处理。 |
db/directsqlx
* * desc : 参数校验函数 * author : 畅雨 * date : 2016.12.13 * desc : * history : 2017.05.28 - 增加主从表关联id的服务端处理。
|
* * desc : 参数校验函数 * author : 畅雨 * date : 2016.12.13 * desc : * history : 2017.05.28 - 增加主从表关联id的服务端处理。 |
otp
Package otp implements both HOTP and TOTP based one time passcodes in a Google Authenticator compatible manner.
|
Package otp implements both HOTP and TOTP based one time passcodes in a Google Authenticator compatible manner. |
surfer
import ( "github.com/henrylee2cn/surfer" "io/ioutil" "log" ) func main() { // Use surf engine resp, err := surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn/surfer", }) if err != nil { log.Fatal(err) } b, err := ioutil.ReadAll(resp.Body) log.Println(string(b), err) // Use phantomjs engine resp, err = surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn", DownloaderID: 1, }) if err != nil { log.Fatal(err) } b, err = ioutil.ReadAll(resp.Body) log.Println(string(b), err) resp.Body.Close() surfer.DestroyJsFiles() }
|
import ( "github.com/henrylee2cn/surfer" "io/ioutil" "log" ) func main() { // Use surf engine resp, err := surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn/surfer", }) if err != nil { log.Fatal(err) } b, err := ioutil.ReadAll(resp.Body) log.Println(string(b), err) // Use phantomjs engine resp, err = surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn", DownloaderID: 1, }) if err != nil { log.Fatal(err) } b, err = ioutil.ReadAll(resp.Body) log.Println(string(b), err) resp.Body.Close() surfer.DestroyJsFiles() } |
uuid
Package uuid generates and inspects UUIDs.
|
Package uuid generates and inspects UUIDs. |
websocket
Package websocket implements the WebSocket protocol defined in RFC 6455.
|
Package websocket implements the WebSocket protocol defined in RFC 6455. |
websocket/examples/autobahn
Command server is a test server for the Autobahn WebSockets Test Suite.
|
Command server is a test server for the Autobahn WebSockets Test Suite. |
murmur3
Native (and fast) implementation of Austin Appleby's MurmurHash3.
|
Native (and fast) implementation of Austin Appleby's MurmurHash3. |
server
A basic freecache server supports redis protocol
|
A basic freecache server supports redis protocol |
Package gracenet provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started.
|
Package gracenet provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started. |
Package logging implements a logging infrastructure for Go.
|
Package logging implements a logging infrastructure for Go. |
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. |
samples
|
|
directsql/common
功能:pongo2模板数据库访问函数 日期:2017.01.06
|
功能:pongo2模板数据库访问函数 日期:2017.01.06 |
directsql/router
* * desc : 系统功能路由注册 * author:畅雨 * date: 2016.05.16 * history: *
|
* * desc : 系统功能路由注册 * author:畅雨 * date: 2016.05.16 * history: * |
directsqlx/common
功能:pongo2模板数据库访问函数 日期:2017.01.06
|
功能:pongo2模板数据库访问函数 日期:2017.01.06 |
directsqlx/router
* * desc : 系统功能路由注册 * author:畅雨 * date: 2016.05.16 * history: *
|
* * desc : 系统功能路由注册 * author:畅雨 * date: 2016.05.16 * history: * |
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 modify: henrylee
|
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 modify: henrylee |
couchbase
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/astaxie/beego/session/couchbase" "github.com/astaxie/beego/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/astaxie/beego/session/couchbase" "github.com/astaxie/beego/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/astaxie/beego/session/memcache" "github.com/astaxie/beego/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/astaxie/beego/session/memcache" "github.com/astaxie/beego/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/astaxie/beego/session/mysql" "github.com/astaxie/beego/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/astaxie/beego/session/mysql" "github.com/astaxie/beego/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/astaxie/beego/session/postgresql" "github.com/astaxie/beego/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/astaxie/beego/session/postgresql" "github.com/astaxie/beego/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/astaxie/beego/session/redis" "github.com/astaxie/beego/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/astaxie/beego/session/redis" "github.com/astaxie/beego/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 swagger struct definition
|
Package swagger struct definition |