Documentation ¶
Overview ¶
Package beego provide a MVC framework beego: an open-source, high-performance, modular, full-stack web framework
It is used for rapid development of RESTful APIs, web apps and backend services in Go. beego is inspired by Tornado, Sinatra and Flask with the added benefit of some Go-specific features such as interfaces and struct embedding.
package main import "github.com/bowhan/beego" func main() { beego.Run() }
more information: http://beego.me
Index ¶
- Constants
- Variables
- func AddAPPStartHook(hf ...hookfunc)
- func AddFuncMap(key string, fn interface{}) error
- func AddNamespace(nl ...*Namespace)
- func AddTemplateExt(ext string)
- func AddViewPath(viewPath string) error
- func Alert(v ...interface{})
- func AssetsCSS(text string) template.HTML
- func AssetsJs(text string) template.HTML
- func BuildTemplate(dir string, files ...string) error
- func Compare(a, b interface{}) (equal bool)
- func CompareNot(a, b interface{}) (equal bool)
- func Critical(v ...interface{})
- func Date(t time.Time, format string) string
- func DateFormat(t time.Time, layout string) (datestring string)
- func DateParse(dateString, format string) (time.Time, error)
- func Debug(v ...interface{})
- func Emergency(v ...interface{})
- func Error(v ...interface{})
- func ExceptMethodAppend(action string)
- func Exception(errCode uint64, ctx *context.Context)
- func ExecuteTemplate(wr io.Writer, name string, data interface{}) error
- func ExecuteViewPathTemplate(wr io.Writer, name string, viewPath string, data interface{}) error
- func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error)
- func HTML2str(html string) string
- func HasTemplateExt(paths string) bool
- func Htmlquote(text string) string
- func Htmlunquote(text string) string
- func Info(v ...interface{})
- func Informational(v ...interface{})
- func InitBeegoBeforeTest(appConfigPath string)
- func LoadAppConfig(adapterName, configPath string) error
- func LogAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int)
- func MapGet(arg1 interface{}, arg2 ...interface{}) (interface{}, error)
- func NotNil(a interface{}) (isNil bool)
- func Notice(v ...interface{})
- func ParseForm(form url.Values, obj interface{}) error
- func Policy(pattern, method string, policy ...PolicyFunc)
- func RenderForm(obj interface{}) template.HTML
- func Run(params ...string)
- func RunWithMiddleWares(addr string, mws ...MiddleWare)
- func SetLevel(l int)
- func SetLogFuncCall(b bool)
- func SetLogger(adaptername string, config string) error
- func SetTemplateFSFunc(fnt templateFSFunc)
- func Str2html(raw string) template.HTML
- func Substr(s string, start, length int) string
- func TestBeegoInit(ap string)
- func Trace(v ...interface{})
- func URLFor(endpoint string, values ...interface{}) string
- func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error
- func Warn(v ...interface{})
- func Warning(v ...interface{})
- type App
- func AddTemplateEngine(extension string, fn templatePreProcessor) *App
- func Any(rootpath string, f FilterFunc) *App
- func AutoPrefix(prefix string, c ControllerInterface) *App
- func AutoRouter(c ControllerInterface) *App
- func DelStaticPath(url string) *App
- func Delete(rootpath string, f FilterFunc) *App
- func ErrorController(c ControllerInterface) *App
- func ErrorHandler(code string, h http.HandlerFunc) *App
- func Get(rootpath string, f FilterFunc) *App
- func Handler(rootpath string, h http.Handler, options ...interface{}) *App
- func Head(rootpath string, f FilterFunc) *App
- func Include(cList ...ControllerInterface) *App
- func InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) *App
- func NewApp() *App
- func Options(rootpath string, f FilterFunc) *App
- func Patch(rootpath string, f FilterFunc) *App
- func Post(rootpath string, f FilterFunc) *App
- func Put(rootpath string, f FilterFunc) *App
- func RESTRouter(rootpath string, c ControllerInterface) *App
- func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App
- func SetStaticPath(url string, path string) *App
- func SetViewsPath(path string) *App
- func UnregisterFixedRoute(fixedRoute string, method string) *App
- type Config
- type Controller
- func (c *Controller) Abort(code string)
- func (c *Controller) CheckXSRFCookie() bool
- func (c *Controller) CustomAbort(status int, body string)
- func (c *Controller) DelSession(name interface{})
- func (c *Controller) Delete()
- func (c *Controller) DestroySession()
- func (c *Controller) Finish()
- func (c *Controller) Get()
- func (c *Controller) GetBool(key string, def ...bool) (bool, error)
- func (c *Controller) GetControllerAndAction() (string, string)
- func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error)
- func (c *Controller) GetFloat(key string, def ...float64) (float64, error)
- func (c *Controller) GetInt(key string, def ...int) (int, error)
- func (c *Controller) GetInt16(key string, def ...int16) (int16, error)
- func (c *Controller) GetInt32(key string, def ...int32) (int32, error)
- func (c *Controller) GetInt64(key string, def ...int64) (int64, error)
- func (c *Controller) GetInt8(key string, def ...int8) (int8, error)
- func (c *Controller) GetSecureCookie(Secret, key string) (string, bool)
- func (c *Controller) GetSession(name interface{}) interface{}
- func (c *Controller) GetString(key string, def ...string) string
- func (c *Controller) GetStrings(key string, def ...[]string) []string
- func (c *Controller) GetUint16(key string, def ...uint16) (uint16, error)
- func (c *Controller) GetUint32(key string, def ...uint32) (uint32, error)
- func (c *Controller) GetUint64(key string, def ...uint64) (uint64, error)
- func (c *Controller) GetUint8(key string, def ...uint8) (uint8, error)
- func (c *Controller) HandlerFunc(fnname string) bool
- func (c *Controller) Head()
- func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{})
- func (c *Controller) Input() url.Values
- func (c *Controller) IsAjax() bool
- func (c *Controller) Mapping(method string, fn func())
- func (c *Controller) Options()
- func (c *Controller) ParseForm(obj interface{}) error
- func (c *Controller) Patch()
- func (c *Controller) Post()
- func (c *Controller) Prepare()
- func (c *Controller) Put()
- func (c *Controller) Redirect(url string, code int)
- func (c *Controller) Render() error
- func (c *Controller) RenderBytes() ([]byte, error)
- func (c *Controller) RenderString() (string, error)
- func (c *Controller) SaveToFile(fromfile, tofile string) error
- func (c *Controller) ServeFormatted(encoding ...bool)
- func (c *Controller) ServeJSON(encoding ...bool)
- func (c *Controller) ServeJSONP()
- func (c *Controller) ServeXML()
- func (c *Controller) ServeYAML()
- func (c *Controller) SessionRegenerateID() (err error)
- func (c *Controller) SetData(data interface{})
- func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{})
- func (c *Controller) SetSession(name interface{}, value interface{})
- func (c *Controller) StartSession() session.Store
- func (c *Controller) StopRun()
- func (c *Controller) Trace()
- func (c *Controller) URLFor(endpoint string, values ...interface{}) string
- func (c *Controller) URLMapping()
- func (c *Controller) XSRFFormHTML() string
- func (c *Controller) XSRFToken() string
- type ControllerComments
- type ControllerCommentsSlice
- type ControllerFilter
- type ControllerFilterComments
- type ControllerImportComments
- type ControllerInfo
- type ControllerInterface
- type ControllerRegister
- func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string)
- func (p *ControllerRegister) AddAuto(c ControllerInterface)
- func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface)
- func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc)
- func (p *ControllerRegister) Any(pattern string, f FilterFunc)
- func (p *ControllerRegister) Delete(pattern string, f FilterFunc)
- func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc
- func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool)
- func (p *ControllerRegister) Get(pattern string, f FilterFunc)
- func (p *ControllerRegister) GetContext() *beecontext.Context
- func (p *ControllerRegister) GiveBackContext(ctx *beecontext.Context)
- func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{})
- func (p *ControllerRegister) Head(pattern string, f FilterFunc)
- func (p *ControllerRegister) Include(cList ...ControllerInterface)
- func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error
- func (p *ControllerRegister) Options(pattern string, f FilterFunc)
- func (p *ControllerRegister) Patch(pattern string, f FilterFunc)
- func (p *ControllerRegister) Post(pattern string, f FilterFunc)
- func (p *ControllerRegister) Put(pattern string, f FilterFunc)
- func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request)
- func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string
- type FileSystem
- type FilterFunc
- type FilterHandler
- type FilterRouter
- type FlashData
- func (fd *FlashData) Error(msg string, args ...interface{})
- func (fd *FlashData) Notice(msg string, args ...interface{})
- func (fd *FlashData) Set(key string, msg string, args ...interface{})
- func (fd *FlashData) Store(c *Controller)
- func (fd *FlashData) Success(msg string, args ...interface{})
- func (fd *FlashData) Warning(msg string, args ...interface{})
- type LinkNamespace
- func NSAfter(filterList ...FilterFunc) LinkNamespace
- func NSAny(rootpath string, f FilterFunc) LinkNamespace
- func NSAutoPrefix(prefix string, c ControllerInterface) LinkNamespace
- func NSAutoRouter(c ControllerInterface) LinkNamespace
- func NSBefore(filterList ...FilterFunc) LinkNamespace
- func NSCond(cond namespaceCond) LinkNamespace
- func NSDelete(rootpath string, f FilterFunc) LinkNamespace
- func NSGet(rootpath string, f FilterFunc) LinkNamespace
- func NSHandler(rootpath string, h http.Handler) LinkNamespace
- func NSHead(rootpath string, f FilterFunc) LinkNamespace
- func NSInclude(cList ...ControllerInterface) LinkNamespace
- func NSNamespace(prefix string, params ...LinkNamespace) LinkNamespace
- func NSOptions(rootpath string, f FilterFunc) LinkNamespace
- func NSPatch(rootpath string, f FilterFunc) LinkNamespace
- func NSPost(rootpath string, f FilterFunc) LinkNamespace
- func NSPut(rootpath string, f FilterFunc) LinkNamespace
- func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) LinkNamespace
- type Listen
- type LogConfig
- type M
- type MiddleWare
- type Namespace
- func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace
- func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace
- func (n *Namespace) Cond(cond namespaceCond) *Namespace
- func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace
- func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Handler(rootpath string, h http.Handler) *Namespace
- func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Include(cList ...ControllerInterface) *Namespace
- func (n *Namespace) Namespace(ns ...*Namespace) *Namespace
- func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace
- func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace
- type PolicyFunc
- type SessionConfig
- type Tree
- type WebConfig
Constants ¶
const ( // VERSION represent beego web framework version. VERSION = "1.12.3" // DEV is for develop DEV = "dev" // PROD is for production PROD = "prod" )
const ( LevelEmergency = iota LevelAlert LevelCritical LevelError LevelWarning LevelNotice LevelInformational LevelDebug )
Log levels to control the logging output. Deprecated: use github.com/bowhan/beego/logs instead.
const ( BeforeStatic = iota BeforeRouter BeforeExec AfterExec FinishRouter )
default filter execution points
Variables ¶
var ( BuildVersion string BuildGitRevision string BuildStatus string BuildTag string BuildTime string GoVersion string GitBranch string )
var ( // BConfig is the default config for Application BConfig *Config // AppConfig is the instance of Config, store the config information from file AppConfig *beegoAppConfig // AppPath is the absolute path to the app AppPath string // GlobalSessions is the instance for the session manager GlobalSessions *session.Manager // WorkPath is the absolute path to project root directory WorkPath string )
var ( // ErrAbort custom error when user stop request handler manually. ErrAbort = errors.New("user stop run") // GlobalControllerRouter store comments with controller. pkgpath+controller:comments GlobalControllerRouter = make(map[string][]ControllerComments) )
var BeeLogger = logs.GetBeeLogger()
BeeLogger references the used application logger. Deprecated: use github.com/bowhan/beego/logs instead.
var ErrorMaps = make(map[string]*errorInfo, 10)
ErrorMaps holds map of http handlers for each error string. there is 10 kinds default error(40x and 50x)
FilterMonitorFunc is default monitor filter when admin module is enable. if this func returns, admin module records qps for this request by condition of this function logic. usage:
func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool { if method == "POST" { return false } if t.Nanoseconds() < 100 { return false } if strings.HasPrefix(requestPath, "/astaxie") { return false } return true } beego.FilterMonitorFunc = MyFilterMonitor.
Functions ¶
func AddAPPStartHook ¶
func AddAPPStartHook(hf ...hookfunc)
AddAPPStartHook is used to register the hookfunc The hookfuncs will run in beego.Run() such as initiating session , starting middleware , building template, starting admin control and so on.
func AddFuncMap ¶
AddFuncMap let user to register a func in the template.
func AddNamespace ¶
func AddNamespace(nl ...*Namespace)
AddNamespace register Namespace into beego.Handler support multi Namespace
func AddTemplateExt ¶
func AddTemplateExt(ext string)
AddTemplateExt add new extension for template.
func AddViewPath ¶ added in v1.8.0
AddViewPath adds a new path to the supported view paths. Can later be used by setting a controller ViewPath to this folder will panic if called after beego.Run()
func Alert ¶ added in v1.4.0
func Alert(v ...interface{})
Alert logs a message at alert level. Deprecated: use github.com/bowhan/beego/logs instead.
func BuildTemplate ¶
BuildTemplate will build all template files in a directory. it makes beego can render any template file in view directory.
func Compare ¶
func Compare(a, b interface{}) (equal bool)
Compare is a quick and dirty comparison function. It will convert whatever you give it to strings and see if the two values are equal. Whitespace is trimmed. Used by the template parser as "eq".
func CompareNot ¶ added in v1.4.3
func CompareNot(a, b interface{}) (equal bool)
CompareNot !Compare
func Critical ¶
func Critical(v ...interface{})
Critical logs a message at critical level. Deprecated: use github.com/bowhan/beego/logs instead.
func DateFormat ¶
DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"
func Debug ¶
func Debug(v ...interface{})
Debug logs a message at debug level. Deprecated: use github.com/bowhan/beego/logs instead.
func Emergency ¶ added in v1.4.0
func Emergency(v ...interface{})
Emergency logs a message at emergency level. Deprecated: use github.com/bowhan/beego/logs instead.
func Error ¶
func Error(v ...interface{})
Error logs a message at error level. Deprecated: use github.com/bowhan/beego/logs instead.
func ExceptMethodAppend ¶
func ExceptMethodAppend(action string)
ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
func Exception ¶ added in v1.7.0
Exception Write HttpStatus with errCode and Exec error handler if exist.
func ExecuteTemplate ¶ added in v1.7.0
ExecuteTemplate applies the template with name to the specified data object, writing the output to wr. A template will be executed safely in parallel.
func ExecuteViewPathTemplate ¶ added in v1.8.0
ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object, writing the output to wr. A template will be executed safely in parallel.
func HasTemplateExt ¶
HasTemplateExt return this path contains supported template extension of beego or not.
func Info ¶
func Info(v ...interface{})
Info compatibility alias for Warning() Deprecated: use github.com/bowhan/beego/logs instead.
func Informational ¶ added in v1.4.0
func Informational(v ...interface{})
Informational logs a message at info level. Deprecated: use github.com/bowhan/beego/logs instead.
func InitBeegoBeforeTest ¶ added in v1.7.1
func InitBeegoBeforeTest(appConfigPath string)
InitBeegoBeforeTest is for test package init
func LoadAppConfig ¶ added in v1.6.1
LoadAppConfig allow developer to apply a config file
func LogAccess ¶ added in v1.12.12
func LogAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int)
LogAccess logging info HTTP Access
func MapGet ¶ added in v1.6.0
func MapGet(arg1 interface{}, arg2 ...interface{}) (interface{}, error)
MapGet getting value from map by keys usage:
Data["m"] = M{ "a": 1, "1": map[string]float64{ "c": 4, }, }
{{ map_get m "a" }} // return 1 {{ map_get m 1 "c" }} // return 4
func Notice ¶ added in v1.4.0
func Notice(v ...interface{})
Notice logs a message at notice level. Deprecated: use github.com/bowhan/beego/logs instead.
func Policy ¶ added in v1.7.2
func Policy(pattern, method string, policy ...PolicyFunc)
Policy Register new policy in beego
func RenderForm ¶
RenderForm will render object to form html. obj must be a struct pointer.
func Run ¶
func Run(params ...string)
Run beego application. beego.Run() default run on HttpPort beego.Run("localhost") beego.Run(":8089") beego.Run("127.0.0.1:8089")
func RunWithMiddleWares ¶ added in v1.9.2
func RunWithMiddleWares(addr string, mws ...MiddleWare)
RunWithMiddleWares Run beego application with middlewares.
func SetLevel ¶
func SetLevel(l int)
SetLevel sets the global log level used by the simple logger. Deprecated: use github.com/bowhan/beego/logs instead.
func SetLogFuncCall ¶
func SetLogFuncCall(b bool)
SetLogFuncCall set the CallDepth, default is 3 Deprecated: use github.com/bowhan/beego/logs instead.
func SetTemplateFSFunc ¶ added in v1.12.12
func SetTemplateFSFunc(fnt templateFSFunc)
SetTemplateFSFunc set default filesystem function
func Trace ¶
func Trace(v ...interface{})
Trace logs a message at trace level. compatibility alias for Warning() Deprecated: use github.com/bowhan/beego/logs instead.
func URLFor ¶ added in v1.6.0
URLFor returns url string with another registered controller handler with params.
usage: URLFor(".index") print URLFor("index") router /login print URLFor("login") print URLFor("login", "next","/"") router /profile/:username print UrlFor("profile", ":username","John Doe") result: / /login /login?next=/ /user/John%20Doe more detail http://beego.me/docs/mvc/controller/urlbuilding.md
func Walk ¶ added in v1.12.12
Walk walks the file tree rooted at root in filesystem, calling walkFn for each file or directory in the tree, including root. All errors that arise visiting files and directories are filtered by walkFn.
Types ¶
type App ¶
type App struct { Handlers *ControllerRegister Server *http.Server }
App defines beego application with a new PatternServeMux.
var ( // BeeApp is an application instance BeeApp *App )
func AddTemplateEngine ¶ added in v1.7.0
AddTemplateEngine add a new templatePreProcessor which support extension
func Any ¶
func Any(rootpath string, f FilterFunc) *App
Any used to register router for all methods usage:
beego.Any("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func AutoPrefix ¶
func AutoPrefix(prefix string, c ControllerInterface) *App
AutoPrefix adds controller handler to BeeApp with prefix. it's same to App.AutoRouterWithPrefix. if beego.AutoPrefix("/admin",&MainContorlller{}) and MainController has methods List and Page, visit the url /admin/main/list to exec List function or /admin/main/page to exec Page function.
func AutoRouter ¶
func AutoRouter(c ControllerInterface) *App
AutoRouter adds defined controller handler to BeeApp. it's same to App.AutoRouter. if beego.AddAuto(&MainContorlller{}) and MainController has methods List and Page, visit the url /main/list to exec List function or /main/page to exec Page function.
func DelStaticPath ¶
DelStaticPath removes the static folder setting in this url pattern in beego application.
func Delete ¶
func Delete(rootpath string, f FilterFunc) *App
Delete used to register router for Delete method usage:
beego.Delete("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func ErrorController ¶ added in v1.4.3
func ErrorController(c ControllerInterface) *App
ErrorController registers ControllerInterface to each http err code string. usage:
beego.ErrorController(&controllers.ErrorController{})
func ErrorHandler ¶ added in v1.6.0
func ErrorHandler(code string, h http.HandlerFunc) *App
ErrorHandler registers http.HandlerFunc to each http err code string. usage:
beego.ErrorHandler("404",NotFound) beego.ErrorHandler("500",InternalServerError)
func Get ¶
func Get(rootpath string, f FilterFunc) *App
Get used to register router for Get method usage:
beego.Get("/", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Handler ¶
Handler used to register a Handler router usage:
beego.Handler("/api", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }))
func Head ¶
func Head(rootpath string, f FilterFunc) *App
Head used to register router for Head method usage:
beego.Head("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Include ¶ added in v1.3.0
func Include(cList ...ControllerInterface) *App
Include will generate router file in the router/xxx.go from the controller's comments usage: beego.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
type BankAccount struct{ beego.Controller }
register the function
func (b *BankAccount)Mapping(){ b.Mapping("ShowAccount" , b.ShowAccount) b.Mapping("ModifyAccount", b.ModifyAccount) }
//@router /account/:id [get]
func (b *BankAccount) ShowAccount(){ //logic }
//@router /account/:id [post]
func (b *BankAccount) ModifyAccount(){ //logic }
the comments @router url methodlist url support all the function Router's pattern methodlist [get post head put delete options *]
func InsertFilter ¶
func InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) *App
InsertFilter adds a FilterFunc with pattern condition and action constant. The pos means action constant including beego.BeforeStatic, beego.BeforeRouter, beego.BeforeExec, beego.AfterExec and beego.FinishRouter. The bool params is for setting the returnOnOutput value (false allows multiple filters to execute)
func Options ¶
func Options(rootpath string, f FilterFunc) *App
Options used to register router for Options method usage:
beego.Options("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Patch ¶
func Patch(rootpath string, f FilterFunc) *App
Patch used to register router for Patch method usage:
beego.Patch("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Post ¶
func Post(rootpath string, f FilterFunc) *App
Post used to register router for Post method usage:
beego.Post("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Put ¶
func Put(rootpath string, f FilterFunc) *App
Put used to register router for Put method usage:
beego.Put("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func RESTRouter ¶
func RESTRouter(rootpath string, c ControllerInterface) *App
RESTRouter adds a restful controller handler to BeeApp. its' controller implements beego.ControllerInterface and defines a param "pattern/:objectId" to visit each resource.
func Router ¶
func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App
Router adds a patterned controller handler to BeeApp. it's an alias method of App.Router. usage:
simple router beego.Router("/admin", &admin.UserController{}) beego.Router("/admin/index", &admin.ArticleController{}) regex router beego.Router("/api/:id([0-9]+)", &controllers.RController{}) custom rules beego.Router("/api/list",&RestController{},"*:ListFood") beego.Router("/api/create",&RestController{},"post:CreateFood") beego.Router("/api/update",&RestController{},"put:UpdateFood") beego.Router("/api/delete",&RestController{},"delete:DeleteFood")
func SetStaticPath ¶
SetStaticPath sets static directory path and proper url pattern in beego application. if beego.SetStaticPath("static","public"), visit /static/* to load static file in folder "public".
func SetViewsPath ¶
SetViewsPath sets view directory path in beego application.
func UnregisterFixedRoute ¶ added in v1.9.2
UnregisterFixedRoute unregisters the route with the specified fixedRoute. It is particularly useful in web applications that inherit most routes from a base webapp via the underscore import, and aim to overwrite only certain paths. The method parameter can be empty or "*" for all HTTP methods, or a particular method type (e.g. "GET" or "POST") for selective removal.
Usage (replace "GET" with "*" for all methods):
beego.UnregisterFixedRoute("/yourpreviouspath", "GET") beego.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage")
type Config ¶ added in v1.3.0
type Config struct { AppName string // Application name RunMode string // Running Mode: dev | prod RouterCaseSensitive bool ServerName string RecoverPanic bool RecoverFunc func(*context.Context) CopyRequestBody bool EnableGzip bool MaxMemory int64 EnableErrorsShow bool EnableErrorsRender bool Listen Listen WebConfig WebConfig Log LogConfig }
Config is the main struct for BConfig
type Controller ¶
type Controller struct { // context data Ctx *context.Context Data map[interface{}]interface{} AppController interface{} // template data TplName string ViewPath string Layout string LayoutSections map[string]string // the key is the section name and the value is the template name TplPrefix string TplExt string EnableRender bool XSRFExpire int EnableXSRF bool // session CruSession session.Store // contains filtered or unexported fields }
Controller defines some basic http request handler operations, such as http context, template and view, session and xsrf.
func (*Controller) Abort ¶
func (c *Controller) Abort(code string)
Abort stops controller handler and show the error data if code is defined in ErrorMap or code string.
func (*Controller) CheckXSRFCookie ¶ added in v1.6.0
func (c *Controller) CheckXSRFCookie() bool
CheckXSRFCookie checks xsrf token in this request is valid or not. the token can provided in request header "X-Xsrftoken" and "X-CsrfToken" or in form field value named as "_xsrf".
func (*Controller) CustomAbort ¶ added in v1.4.0
func (c *Controller) CustomAbort(status int, body string)
CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.
func (*Controller) DelSession ¶
func (c *Controller) DelSession(name interface{})
DelSession removes value from session.
func (*Controller) Delete ¶
func (c *Controller) Delete()
Delete adds a request function to handle DELETE request.
func (*Controller) DestroySession ¶
func (c *Controller) DestroySession()
DestroySession cleans session data and session cookie.
func (*Controller) Finish ¶
func (c *Controller) Finish()
Finish runs after request function execution.
func (*Controller) Get ¶
func (c *Controller) Get()
Get adds a request function to handle GET request.
func (*Controller) GetBool ¶
func (c *Controller) GetBool(key string, def ...bool) (bool, error)
GetBool returns input value as bool or the default value while it's present and input is blank.
func (*Controller) GetControllerAndAction ¶
func (c *Controller) GetControllerAndAction() (string, string)
GetControllerAndAction gets the executing controller name and action name.
func (*Controller) GetFile ¶
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error)
GetFile returns the file data in file upload field named as key. it returns the first one of multi-uploaded files.
func (*Controller) GetFiles ¶ added in v1.5.0
func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error)
GetFiles return multi-upload files files, err:=c.GetFiles("myfiles")
if err != nil { http.Error(w, err.Error(), http.StatusNoContent) return }
for i, _ := range files { //for each fileheader, get a handle to the actual file file, err := files[i].Open() defer file.Close() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } //create destination file making sure the path is writeable. dst, err := os.Create("upload/" + files[i].Filename) defer dst.Close() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } //copy the uploaded file to the destination file if _, err := io.Copy(dst, file); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
func (*Controller) GetFloat ¶
func (c *Controller) GetFloat(key string, def ...float64) (float64, error)
GetFloat returns input value as float64 or the default value while it's present and input is blank.
func (*Controller) GetInt ¶
func (c *Controller) GetInt(key string, def ...int) (int, error)
GetInt returns input as an int or the default value while it's present and input is blank
func (*Controller) GetInt16 ¶ added in v1.4.2
func (c *Controller) GetInt16(key string, def ...int16) (int16, error)
GetInt16 returns input as an int16 or the default value while it's present and input is blank
func (*Controller) GetInt32 ¶ added in v1.4.2
func (c *Controller) GetInt32(key string, def ...int32) (int32, error)
GetInt32 returns input as an int32 or the default value while it's present and input is blank
func (*Controller) GetInt64 ¶ added in v1.4.2
func (c *Controller) GetInt64(key string, def ...int64) (int64, error)
GetInt64 returns input value as int64 or the default value while it's present and input is blank.
func (*Controller) GetInt8 ¶ added in v1.4.2
func (c *Controller) GetInt8(key string, def ...int8) (int8, error)
GetInt8 return input as an int8 or the default value while it's present and input is blank
func (*Controller) GetSecureCookie ¶
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool)
GetSecureCookie returns decoded cookie value from encoded browser cookie values.
func (*Controller) GetSession ¶
func (c *Controller) GetSession(name interface{}) interface{}
GetSession gets value from session.
func (*Controller) GetString ¶
func (c *Controller) GetString(key string, def ...string) string
GetString returns the input value by key string or the default value while it's present and input is blank
func (*Controller) GetStrings ¶
func (c *Controller) GetStrings(key string, def ...[]string) []string
GetStrings returns the input string slice by key string or the default value while it's present and input is blank it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
func (*Controller) GetUint16 ¶ added in v1.7.2
func (c *Controller) GetUint16(key string, def ...uint16) (uint16, error)
GetUint16 returns input as an uint16 or the default value while it's present and input is blank
func (*Controller) GetUint32 ¶ added in v1.7.2
func (c *Controller) GetUint32(key string, def ...uint32) (uint32, error)
GetUint32 returns input as an uint32 or the default value while it's present and input is blank
func (*Controller) GetUint64 ¶ added in v1.7.2
func (c *Controller) GetUint64(key string, def ...uint64) (uint64, error)
GetUint64 returns input value as uint64 or the default value while it's present and input is blank.
func (*Controller) GetUint8 ¶ added in v1.7.2
func (c *Controller) GetUint8(key string, def ...uint8) (uint8, error)
GetUint8 return input as an uint8 or the default value while it's present and input is blank
func (*Controller) HandlerFunc ¶ added in v1.3.0
func (c *Controller) HandlerFunc(fnname string) bool
HandlerFunc call function with the name
func (*Controller) Head ¶
func (c *Controller) Head()
Head adds a request function to handle HEAD request.
func (*Controller) Init ¶
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{})
Init generates default values of controller operations.
func (*Controller) Input ¶
func (c *Controller) Input() url.Values
Input returns the input data map from POST or PUT request body and query string.
func (*Controller) IsAjax ¶
func (c *Controller) IsAjax() bool
IsAjax returns this request is ajax or not.
func (*Controller) Mapping ¶ added in v1.3.0
func (c *Controller) Mapping(method string, fn func())
Mapping the method to function
func (*Controller) Options ¶
func (c *Controller) Options()
Options adds a request function to handle OPTIONS request.
func (*Controller) ParseForm ¶
func (c *Controller) ParseForm(obj interface{}) error
ParseForm maps input data map to obj struct.
func (*Controller) Patch ¶
func (c *Controller) Patch()
Patch adds a request function to handle PATCH request.
func (*Controller) Post ¶
func (c *Controller) Post()
Post adds a request function to handle POST request.
func (*Controller) Prepare ¶
func (c *Controller) Prepare()
Prepare runs after Init before request function execution.
func (*Controller) Put ¶
func (c *Controller) Put()
Put adds a request function to handle PUT request.
func (*Controller) Redirect ¶
func (c *Controller) Redirect(url string, code int)
Redirect sends the redirection response to url with status code.
func (*Controller) Render ¶
func (c *Controller) Render() error
Render sends the response with rendered template bytes as text/html type.
func (*Controller) RenderBytes ¶
func (c *Controller) RenderBytes() ([]byte, error)
RenderBytes returns the bytes of rendered template string. Do not send out response.
func (*Controller) RenderString ¶
func (c *Controller) RenderString() (string, error)
RenderString returns the rendered template string. Do not send out response.
func (*Controller) SaveToFile ¶
func (c *Controller) SaveToFile(fromfile, tofile string) error
SaveToFile saves uploaded file to new path. it only operates the first one of mutil-upload form file field.
func (*Controller) ServeFormatted ¶
func (c *Controller) ServeFormatted(encoding ...bool)
ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
func (*Controller) ServeJSON ¶ added in v1.6.0
func (c *Controller) ServeJSON(encoding ...bool)
ServeJSON sends a json response with encoding charset.
func (*Controller) ServeJSONP ¶ added in v1.6.0
func (c *Controller) ServeJSONP()
ServeJSONP sends a jsonp response.
func (*Controller) ServeXML ¶ added in v1.6.0
func (c *Controller) ServeXML()
ServeXML sends xml response.
func (*Controller) ServeYAML ¶ added in v1.10.0
func (c *Controller) ServeYAML()
ServeYAML sends yaml response.
func (*Controller) SessionRegenerateID ¶
func (c *Controller) SessionRegenerateID() (err error)
SessionRegenerateID regenerates session id for this session. the session data have no changes.
func (*Controller) SetData ¶ added in v1.10.0
func (c *Controller) SetData(data interface{})
SetData set the data depending on the accepted
func (*Controller) SetSecureCookie ¶
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{})
SetSecureCookie puts value into cookie after encoded the value.
func (*Controller) SetSession ¶
func (c *Controller) SetSession(name interface{}, value interface{})
SetSession puts value into session.
func (*Controller) StartSession ¶
func (c *Controller) StartSession() session.Store
StartSession starts session and load old session data info this controller.
func (*Controller) StopRun ¶
func (c *Controller) StopRun()
StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
func (*Controller) Trace ¶ added in v1.12.12
func (c *Controller) Trace()
Trace adds a request function to handle Trace request. this method SHOULD NOT be overridden. https://tools.ietf.org/html/rfc7231#section-4.3.8 The TRACE method requests a remote, application-level loop-back of the request message. The final recipient of the request SHOULD reflect the message received, excluding some fields described below, back to the client as the message body of a 200 (OK) response with a Content-Type of "message/http" (Section 8.3.1 of [RFC7230]).
func (*Controller) URLFor ¶ added in v1.6.0
func (c *Controller) URLFor(endpoint string, values ...interface{}) string
URLFor does another controller handler in this request function. it goes to this controller method if endpoint is not clear.
func (*Controller) URLMapping ¶ added in v1.3.0
func (c *Controller) URLMapping()
URLMapping register the internal Controller router.
func (*Controller) XSRFFormHTML ¶ added in v1.6.0
func (c *Controller) XSRFFormHTML() string
XSRFFormHTML writes an input field contains xsrf token value.
func (*Controller) XSRFToken ¶ added in v1.6.0
func (c *Controller) XSRFToken() string
XSRFToken creates a CSRF token string and returns.
type ControllerComments ¶ added in v1.3.0
type ControllerComments struct { Method string Router string Filters []*ControllerFilter ImportComments []*ControllerImportComments FilterComments []*ControllerFilterComments AllowHTTPMethods []string Params []map[string]string MethodParams []*param.MethodParam }
ControllerComments store the comment for the controller method
type ControllerCommentsSlice ¶ added in v1.9.0
type ControllerCommentsSlice []ControllerComments
ControllerCommentsSlice implements the sort interface
func (ControllerCommentsSlice) Len ¶ added in v1.9.0
func (p ControllerCommentsSlice) Len() int
func (ControllerCommentsSlice) Less ¶ added in v1.9.0
func (p ControllerCommentsSlice) Less(i, j int) bool
func (ControllerCommentsSlice) Swap ¶ added in v1.9.0
func (p ControllerCommentsSlice) Swap(i, j int)
type ControllerFilter ¶ added in v1.12.12
type ControllerFilter struct { Pattern string Pos int Filter FilterFunc ReturnOnOutput bool ResetParams bool }
ControllerFilter store the filter for controller
type ControllerFilterComments ¶ added in v1.12.12
type ControllerFilterComments struct { Pattern string Pos int Filter string // NOQA ReturnOnOutput bool ResetParams bool }
ControllerFilterComments store the comment for controller level filter
type ControllerImportComments ¶ added in v1.12.12
ControllerImportComments store the import comment for controller needed
type ControllerInfo ¶ added in v1.8.1
type ControllerInfo struct {
// contains filtered or unexported fields
}
ControllerInfo holds information about the controller.
func (*ControllerInfo) GetPattern ¶ added in v1.12.12
func (c *ControllerInfo) GetPattern() string
type ControllerInterface ¶
type ControllerInterface interface { Init(ct *context.Context, controllerName, actionName string, app interface{}) Prepare() Get() Post() Delete() Put() Head() Patch() Options() Trace() Finish() Render() error XSRFToken() string CheckXSRFCookie() bool HandlerFunc(fn string) bool URLMapping() }
ControllerInterface is an interface to uniform all controller handler.
type ControllerRegister ¶ added in v1.6.0
type ControllerRegister struct {
// contains filtered or unexported fields
}
ControllerRegister containers registered router rules, controller handlers and filters.
func NewControllerRegister ¶ added in v1.3.0
func NewControllerRegister() *ControllerRegister
NewControllerRegister returns a new ControllerRegister.
func (*ControllerRegister) Add ¶ added in v1.6.0
func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string)
Add controller handler and pattern rules to ControllerRegister. usage:
default methods is the same name as method Add("/user",&UserController{}) Add("/api/list",&RestController{},"*:ListFood") Add("/api/create",&RestController{},"post:CreateFood") Add("/api/update",&RestController{},"put:UpdateFood") Add("/api/delete",&RestController{},"delete:DeleteFood") Add("/api",&RestController{},"get,post:ApiFunc" Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
func (*ControllerRegister) AddAuto ¶ added in v1.6.0
func (p *ControllerRegister) AddAuto(c ControllerInterface)
AddAuto router to ControllerRegister. example beego.AddAuto(&MainContorlller{}), MainController has method List and Page. visit the url /main/list to execute List function /main/page to execute Page function.
func (*ControllerRegister) AddAutoPrefix ¶ added in v1.6.0
func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface)
AddAutoPrefix Add auto router to ControllerRegister with prefix. example beego.AddAutoPrefix("/admin",&MainContorlller{}), MainController has method List and Page. visit the url /admin/main/list to execute List function /admin/main/page to execute Page function.
func (*ControllerRegister) AddMethod ¶ added in v1.6.0
func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc)
AddMethod add http method router usage:
AddMethod("get","/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) Any ¶ added in v1.6.0
func (p *ControllerRegister) Any(pattern string, f FilterFunc)
Any add all method usage:
Any("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) Delete ¶ added in v1.6.0
func (p *ControllerRegister) Delete(pattern string, f FilterFunc)
Delete add delete method usage:
Delete("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) FindPolicy ¶ added in v1.7.2
func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc
FindPolicy Find Router info for URL
func (*ControllerRegister) FindRouter ¶ added in v1.7.0
func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool)
FindRouter Find Router info for URL
func (*ControllerRegister) Get ¶ added in v1.6.0
func (p *ControllerRegister) Get(pattern string, f FilterFunc)
Get add get method usage:
Get("/", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) GetContext ¶ added in v1.12.12
func (p *ControllerRegister) GetContext() *beecontext.Context
GetContext returns a context from pool, so usually you should remember to call Reset function to clean the context And don't forget to give back context to pool example:
ctx := p.GetContext() ctx.Reset(w, q) defer p.GiveBackContext(ctx)
func (*ControllerRegister) GiveBackContext ¶ added in v1.12.12
func (p *ControllerRegister) GiveBackContext(ctx *beecontext.Context)
GiveBackContext put the ctx into pool so that it could be reuse
func (*ControllerRegister) Handler ¶ added in v1.6.0
func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{})
Handler add user defined Handler
func (*ControllerRegister) Head ¶ added in v1.6.0
func (p *ControllerRegister) Head(pattern string, f FilterFunc)
Head add head method usage:
Head("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) Include ¶ added in v1.6.0
func (p *ControllerRegister) Include(cList ...ControllerInterface)
Include only when the Runmode is dev will generate router file in the router/auto.go from the controller Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
func (*ControllerRegister) InsertFilter ¶ added in v1.6.0
func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error
InsertFilter Add a FilterFunc with pattern rule and action constant. params is for:
- setting the returnOnOutput value (false allows multiple filters to execute)
- determining whether or not params need to be reset.
func (*ControllerRegister) Options ¶ added in v1.6.0
func (p *ControllerRegister) Options(pattern string, f FilterFunc)
Options add options method usage:
Options("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) Patch ¶ added in v1.6.0
func (p *ControllerRegister) Patch(pattern string, f FilterFunc)
Patch add patch method usage:
Patch("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) Post ¶ added in v1.6.0
func (p *ControllerRegister) Post(pattern string, f FilterFunc)
Post add post method usage:
Post("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) Put ¶ added in v1.6.0
func (p *ControllerRegister) Put(pattern string, f FilterFunc)
Put add put method usage:
Put("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegister) ServeHTTP ¶ added in v1.6.0
func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request)
Implement http.Handler interface.
func (*ControllerRegister) URLFor ¶ added in v1.6.0
func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string
URLFor does another controller handler in this request function. it can access any controller method.
type FileSystem ¶ added in v1.12.12
type FileSystem struct { }
type FilterFunc ¶
FilterFunc defines a filter function which is invoked before the controller handler is executed.
type FilterHandler ¶ added in v1.4.2
type FilterHandler interface {
Filter(*beecontext.Context) bool
}
FilterHandler is an interface for
var ( // HTTPMETHOD list the supported http methods. HTTPMETHOD = map[string]bool{ "GET": true, "POST": true, "PUT": true, "DELETE": true, "PATCH": true, "OPTIONS": true, "HEAD": true, "TRACE": true, "CONNECT": true, "MKCOL": true, "COPY": true, "MOVE": true, "PROPFIND": true, "PROPPATCH": true, "LOCK": true, "UNLOCK": true, } // DefaultAccessLogFilter will skip the accesslog if return true DefaultAccessLogFilter FilterHandler = &logFilter{} )
type FilterRouter ¶
type FilterRouter struct {
// contains filtered or unexported fields
}
FilterRouter defines a filter operation which is invoked before the controller handler is executed. It can match the URL against a pattern, and execute a filter function when a request with a matching URL arrives.
func (*FilterRouter) ValidRouter ¶
func (f *FilterRouter) ValidRouter(url string, ctx *context.Context) bool
ValidRouter checks if the current request is matched by this filter. If the request is matched, the values of the URL parameters defined by the filter pattern are also returned.
type FlashData ¶
FlashData is a tools to maintain data when using across request.
func ReadFromRequest ¶
func ReadFromRequest(c *Controller) *FlashData
ReadFromRequest parsed flash data from encoded values in cookie.
func (*FlashData) Store ¶
func (fd *FlashData) Store(c *Controller)
Store does the saving operation of flash data. the data are encoded and saved in cookie.
type LinkNamespace ¶ added in v1.6.0
type LinkNamespace func(*Namespace)
LinkNamespace used as link action
func NSAfter ¶ added in v1.3.0
func NSAfter(filterList ...FilterFunc) LinkNamespace
NSAfter add Namespace FinishRouter filter
func NSAny ¶ added in v1.3.0
func NSAny(rootpath string, f FilterFunc) LinkNamespace
NSAny call Namespace Any
func NSAutoPrefix ¶ added in v1.3.0
func NSAutoPrefix(prefix string, c ControllerInterface) LinkNamespace
NSAutoPrefix call Namespace AutoPrefix
func NSAutoRouter ¶ added in v1.3.0
func NSAutoRouter(c ControllerInterface) LinkNamespace
NSAutoRouter call Namespace AutoRouter
func NSBefore ¶ added in v1.3.0
func NSBefore(filterList ...FilterFunc) LinkNamespace
NSBefore Namespace BeforeRouter filter
func NSCond ¶ added in v1.3.0
func NSCond(cond namespaceCond) LinkNamespace
NSCond is Namespace Condition
func NSDelete ¶ added in v1.3.0
func NSDelete(rootpath string, f FilterFunc) LinkNamespace
NSDelete call Namespace Delete
func NSGet ¶ added in v1.3.0
func NSGet(rootpath string, f FilterFunc) LinkNamespace
NSGet call Namespace Get
func NSHandler ¶ added in v1.6.1
func NSHandler(rootpath string, h http.Handler) LinkNamespace
NSHandler add handler
func NSHead ¶ added in v1.3.0
func NSHead(rootpath string, f FilterFunc) LinkNamespace
NSHead call Namespace Head
func NSInclude ¶ added in v1.3.0
func NSInclude(cList ...ControllerInterface) LinkNamespace
NSInclude Namespace Include ControllerInterface
func NSNamespace ¶ added in v1.3.0
func NSNamespace(prefix string, params ...LinkNamespace) LinkNamespace
NSNamespace add sub Namespace
func NSOptions ¶ added in v1.3.0
func NSOptions(rootpath string, f FilterFunc) LinkNamespace
NSOptions call Namespace Options
func NSPatch ¶ added in v1.3.0
func NSPatch(rootpath string, f FilterFunc) LinkNamespace
NSPatch call Namespace Patch
func NSPost ¶ added in v1.3.0
func NSPost(rootpath string, f FilterFunc) LinkNamespace
NSPost call Namespace Post
func NSPut ¶ added in v1.3.0
func NSPut(rootpath string, f FilterFunc) LinkNamespace
NSPut call Namespace Put
func NSRouter ¶ added in v1.3.0
func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) LinkNamespace
NSRouter call Namespace Router
type Listen ¶ added in v1.6.0
type Listen struct { Graceful bool // Graceful means use graceful module to start the server ServerTimeOut int64 ListenTCP4 bool EnableHTTP bool HTTPAddr string HTTPPort int AutoTLS bool Domains []string TLSCacheDir string EnableHTTPS bool EnableMutualHTTPS bool HTTPSAddr string HTTPSPort int HTTPSCertFile string HTTPSKeyFile string TrustCaFile string ClientAuth tls.ClientAuthType EnableAdmin bool AdminAddr string AdminPort int EnableFcgi bool EnableStdIo bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O }
Listen holds for http and https related config
type LogConfig ¶ added in v1.6.0
type LogConfig struct { AccessLogs bool EnableStaticLogs bool // log static files requests default: false AccessLogsFormat string // access log format: JSON_FORMAT, APACHE_FORMAT or empty string FileLineNum bool Outputs map[string]string // Store Adaptor : config }
LogConfig holds Log related config
type MiddleWare ¶ added in v1.9.2
MiddleWare function for http.Handler
type Namespace ¶
type Namespace struct {
// contains filtered or unexported fields
}
Namespace is store all the info
func NewNamespace ¶
func NewNamespace(prefix string, params ...LinkNamespace) *Namespace
NewNamespace get new Namespace
func (*Namespace) Any ¶
func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace
Any same as beego.Any refer: https://godoc.org/github.com/bowhan/beego#Any
func (*Namespace) AutoPrefix ¶
func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace
AutoPrefix same as beego.AutoPrefix refer: https://godoc.org/github.com/bowhan/beego#AutoPrefix
func (*Namespace) AutoRouter ¶
func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace
AutoRouter same as beego.AutoRouter refer: https://godoc.org/github.com/bowhan/beego#AutoRouter
func (*Namespace) Cond ¶
Cond set condition function if cond return true can run this namespace, else can't usage:
ns.Cond(func (ctx *context.Context) bool{ if ctx.Input.Domain() == "api.beego.me" { return true } return false })
Cond as the first filter
func (*Namespace) Delete ¶
func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace
Delete same as beego.Delete refer: https://godoc.org/github.com/bowhan/beego#Delete
func (*Namespace) Filter ¶
func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace
Filter add filter in the Namespace action has before & after FilterFunc usage:
Filter("before", func (ctx *context.Context){ _, ok := ctx.Input.Session("uid").(int) if !ok && ctx.Request.RequestURI != "/login" { ctx.Redirect(302, "/login") } })
func (*Namespace) Get ¶
func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace
Get same as beego.Get refer: https://godoc.org/github.com/bowhan/beego#Get
func (*Namespace) Handler ¶
Handler same as beego.Handler refer: https://godoc.org/github.com/bowhan/beego#Handler
func (*Namespace) Head ¶
func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace
Head same as beego.Head refer: https://godoc.org/github.com/bowhan/beego#Head
func (*Namespace) Include ¶ added in v1.3.0
func (n *Namespace) Include(cList ...ControllerInterface) *Namespace
Include add include class refer: https://godoc.org/github.com/bowhan/beego#Include
func (*Namespace) Namespace ¶
Namespace add nest Namespace usage: ns := beego.NewNamespace(“/v1”). Namespace(
beego.NewNamespace("/shop"). Get("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("shopinfo")) }), beego.NewNamespace("/order"). Get("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("orderinfo")) }), beego.NewNamespace("/crm"). Get("/:id", func(ctx *context.Context) { ctx.Output.Body([]byte("crminfo")) }),
)
func (*Namespace) Options ¶
func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace
Options same as beego.Options refer: https://godoc.org/github.com/bowhan/beego#Options
func (*Namespace) Patch ¶
func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace
Patch same as beego.Patch refer: https://godoc.org/github.com/bowhan/beego#Patch
func (*Namespace) Post ¶
func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace
Post same as beego.Post refer: https://godoc.org/github.com/bowhan/beego#Post
func (*Namespace) Put ¶
func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace
Put same as beego.Put refer: https://godoc.org/github.com/bowhan/beego#Put
func (*Namespace) Router ¶
func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace
Router same as beego.Rourer refer: https://godoc.org/github.com/bowhan/beego#Router
type PolicyFunc ¶ added in v1.7.2
PolicyFunc defines a policy function which is invoked before the controller handler is executed.
type SessionConfig ¶ added in v1.6.0
type SessionConfig struct { SessionOn bool SessionProvider string SessionName string SessionGCMaxLifetime int64 SessionProviderConfig string SessionCookieLifeTime int SessionAutoSetCookie bool SessionDomain string SessionDisableHTTPOnly bool // used to allow for cross domain cookies/javascript cookies. SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers SessionNameInHTTPHeader string SessionEnableSidInURLQuery bool // enable get the sessionId from Url Query params SessionCookieSameSite http.SameSite }
SessionConfig holds session related config
type Tree ¶ added in v1.3.0
type Tree struct {
// contains filtered or unexported fields
}
Tree has three elements: FixRouter/wildcard/leaves fixRouter stores Fixed Router wildcard stores params leaves store the endpoint information
type WebConfig ¶ added in v1.6.0
type WebConfig struct { AutoRender bool EnableDocs bool FlashName string FlashSeparator string DirectoryIndex bool StaticDir map[string]string StaticExtensionsToGzip []string StaticCacheFileSize int StaticCacheFileNum int TemplateLeft string TemplateRight string ViewsPath string EnableXSRF bool XSRFKey string XSRFExpire int XSRFSecure bool XSRFHttpOnly bool Session SessionConfig }
WebConfig holds web related config
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package cache provide a Cache interface and some implement engine Usage:
|
Package cache provide a Cache interface and some implement engine Usage: |
memcache
Package memcache for cache provider
|
Package memcache for cache provider |
redis
Package redis for cache provider
|
Package redis for cache provider |
Package config is used to parse config.
|
Package config is used to parse config. |
env
Package env is used to parse environment.
|
Package env is used to parse environment. |
xml
Package xml for config provider.
|
Package xml for config provider. |
yaml
Package yaml for config provider
|
Package yaml for config provider |
Package context provide the context utils Usage:
|
Package context provide the context utils Usage: |
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
|
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/ |
Package httplib is used as http.Client Usage:
|
Package httplib is used as http.Client Usage: |
Package logs provide a general log interface Usage:
|
Package logs provide a general log interface Usage: |
alils
Package alils implements the SDK(v0.5.0) of Simple Log Service(abbr.
|
Package alils implements the SDK(v0.5.0) of Simple Log Service(abbr. |
Package migration enables you to generate migrations back and forth.
|
Package migration enables you to generate migrations back and forth. |
Package orm provide ORM for MySQL/PostgreSQL/sqlite Simple Usage
|
Package orm provide ORM for MySQL/PostgreSQL/sqlite Simple Usage |
plugins
|
|
apiauth
Package apiauth provides handlers to enable apiauth support.
|
Package apiauth provides handlers to enable apiauth support. |
auth
Package auth provides handlers to enable basic auth support.
|
Package auth provides handlers to enable basic auth support. |
authz
Package authz provides handlers to enable ACL, RBAC, ABAC authorization support.
|
Package authz provides handlers to enable ACL, RBAC, ABAC authorization support. |
cors
Package cors provides handlers to enable CORS support.
|
Package cors provides handlers to enable CORS support. |
Package session provider
|
Package session provider |
couchbase
Package couchbase for session provider
|
Package couchbase for session provider |
ledis
Package ledis provide session Provider
|
Package ledis provide session Provider |
memcache
Package memcache for session provider
|
Package memcache for session provider |
mysql
Package mysql for session provider
|
Package mysql for session provider |
postgres
Package postgres for session provider
|
Package postgres for session provider |
redis
Package redis for session provider
|
Package redis for session provider |
redis_cluster
Package redis for session provider
|
Package redis for session provider |
redis_sentinel
Package redis for session provider
|
Package redis for session provider |
Package swagger struct definition
|
Package swagger struct definition |
Package toolbox healthcheck
|
Package toolbox healthcheck |
captcha
Package captcha implements generation and verification of image CAPTCHAs.
|
Package captcha implements generation and verification of image CAPTCHAs. |
pagination
Package pagination provides utilities to setup a paginator within the context of a http request.
|
Package pagination provides utilities to setup a paginator within the context of a http request. |
Package validation for validations
|
Package validation for validations |