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/astaxie/beego" func main() { beego.Run() }
more information: http://beego.me
const ( VERSION = "1.12.3" DEV = "dev" PROD = "prod" )View Source
const ( LevelEmergency = iota LevelAlert LevelCritical LevelError LevelWarning LevelNotice LevelInformational LevelDebug )
Log levels to control the logging output. Deprecated: use github.com/astaxie/beego/logs instead.
View Sourceconst ( BeforeStatic = iota BeforeRouter BeforeExec AfterExec FinishRouter )
default filter execution points
BeeLogger references the used application logger. Deprecated: use github.com/astaxie/beego/logs instead.
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.
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.
AddFuncMap let user to register a func in the template.
AddNamespace register Namespace into beego.Handler support multi Namespace
func AddTemplateExt(ext string)
AddTemplateExt add new extension for template.
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(v ...interface{})
Alert logs a message at alert level. Deprecated: use github.com/astaxie/beego/logs instead.
AssetsCSS returns stylesheet link tag with src string.
AssetsJs returns script tag with src string.
BuildTemplate will build all template files in a directory. it makes beego can render any template file in view directory.
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(a, b interface{}) (equal bool)
CompareNot !Compare
func Critical(v ...interface{})
Critical logs a message at critical level. Deprecated: use github.com/astaxie/beego/logs instead.
Date takes a PHP like date func to Go's time format.
DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"
DateParse Parse Date use PHP time format.
func Debug(v ...interface{})
Debug logs a message at debug level. Deprecated: use github.com/astaxie/beego/logs instead.
func Emergency(v ...interface{})
Emergency logs a message at emergency level. Deprecated: use github.com/astaxie/beego/logs instead.
func Error(v ...interface{})
Error logs a message at error level. Deprecated: use github.com/astaxie/beego/logs instead.
func ExceptMethodAppend(action string)
ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
Exception Write HttpStatus with errCode and Exec error handler if exist.
ExecuteTemplate applies the template with name to the specified data object, writing the output to wr. A template will be executed safely in parallel.
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 GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error)
GetConfig get the Appconfig
HTML2str returns escaping text convert from html.
HasTemplateExt return this path contains supported template extension of beego or not.
Htmlquote returns quoted html string.
Htmlunquote returns unquoted html string.
func Info(v ...interface{})
Info compatibility alias for Warning() Deprecated: use github.com/astaxie/beego/logs instead.
func Informational(v ...interface{})
Informational logs a message at info level. Deprecated: use github.com/astaxie/beego/logs instead.
func InitBeegoBeforeTest(appConfigPath string)
InitBeegoBeforeTest is for test package init
func LoadAppConfig(adapterName, configPath string) error
LoadAppConfig allow developer to apply a config file
LogAccess logging info HTTP Access
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 NotNil(a interface{}) (isNil bool)
NotNil the same as CompareNot
func Notice(v ...interface{})
Notice logs a message at notice level. Deprecated: use github.com/astaxie/beego/logs instead.
ParseForm will parse form values to struct via tag.
Policy Register new policy in beego
RenderForm will render object to form html. obj must be a struct pointer.
Run beego application. beego.Run() default run on HttpPort beego.Run("localhost") beego.Run(":8089") beego.Run("127.0.0.1:8089")
RunWithMiddleWares Run beego application with middlewares.
SetLevel sets the global log level used by the simple logger. Deprecated: use github.com/astaxie/beego/logs instead.
func SetLogFuncCall(b bool)
SetLogFuncCall set the CallDepth, default is 3 Deprecated: use github.com/astaxie/beego/logs instead.
SetLogger sets a new logger. Deprecated: use github.com/astaxie/beego/logs instead.
func SetTemplateFSFunc(fnt templateFSFunc)
SetTemplateFSFunc set default filesystem function
Str2html Convert string to template.HTML type.
Substr returns the substr from start to length.
TestBeegoInit is for test package init
func Trace(v ...interface{})
Trace logs a message at trace level. compatibility alias for Warning() Deprecated: use github.com/astaxie/beego/logs instead.
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
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.
func Warn(v ...interface{})
Warn compatibility alias for Warning() Deprecated: use github.com/astaxie/beego/logs instead.
func Warning(v ...interface{})
Warning logs a message at warning level. Deprecated: use github.com/astaxie/beego/logs instead.
App defines beego application with a new PatternServeMux.
func AddTemplateEngine(extension string, fn templatePreProcessor) *App
AddTemplateEngine add a new templatePreProcessor which support extension
Any used to register router for all methods usage:
beego.Any("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
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.
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.
DelStaticPath removes the static folder setting in this url pattern in beego application.
Delete used to register router for Delete method usage:
beego.Delete("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
ErrorController registers ControllerInterface to each http err code string. usage:
beego.ErrorController(&controllers.ErrorController{})func ErrorHandler ¶ added in v1.6.0
ErrorHandler registers http.HandlerFunc to each http err code string. usage:
beego.ErrorHandler("404",NotFound) beego.ErrorHandler("500",InternalServerError)
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)) }))
Head used to register router for Head method usage:
beego.Head("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
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 *]
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)
NewApp returns a new beego application.
Options used to register router for Options method usage:
beego.Options("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Patch used to register router for Patch method usage:
beego.Patch("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Post used to register router for Post method usage:
beego.Post("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Put used to register router for Put method usage:
beego.Put("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
RESTRouter adds a restful controller handler to BeeApp. its' controller implements beego.ControllerInterface and defines a param "pattern/:objectId" to visit each resource.
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")
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".
SetViewsPath sets view directory path in beego application.
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")
Config is the main struct for BConfig
Controller defines some basic http request handler operations, such as http context, template and view, session and xsrf.
Abort stops controller handler and show the error data if code is defined in ErrorMap or code string.
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".
CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.
DelSession removes value from session.
Delete adds a request function to handle DELETE request.
DestroySession cleans session data and session cookie.
Finish runs after request function execution.
Get adds a request function to handle GET request.
GetBool returns input value as bool or the default value while it's present and input is blank.
func (*Controller) GetControllerAndAction ¶GetControllerAndAction gets the executing controller name and action name.
GetFile returns the file data in file upload field named as key. it returns the first one of multi-uploaded files.
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 } }
GetFloat returns input value as float64 or the default value while it's present and input is blank.
GetInt returns input as an int or the default value while it's present and input is blank
GetInt16 returns input as an int16 or the default value while it's present and input is blank
GetInt32 returns input as an int32 or the default value while it's present and input is blank
GetInt64 returns input value as int64 or the default value while it's present and input is blank.
GetInt8 return input as an int8 or the default value while it's present and input is blank
GetSecureCookie returns decoded cookie value from encoded browser cookie values.
func (c *Controller) GetSession(name interface{}) interface{}
GetSession gets value from session.
GetString returns the input value by key string or the default value while it's present and input is blank
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.
GetUint16 returns input as an uint16 or the default value while it's present and input is blank
GetUint32 returns input as an uint32 or the default value while it's present and input is blank
GetUint64 returns input value as uint64 or the default value while it's present and input is blank.
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.0HandlerFunc call function with the name
Head adds a request function to handle HEAD request.
Init generates default values of controller operations.
Input returns the input data map from POST or PUT request body and query string.
IsAjax returns this request is ajax or not.
Mapping the method to function
Options adds a request function to handle OPTIONS request.
ParseForm maps input data map to obj struct.
Patch adds a request function to handle PATCH request.
Post adds a request function to handle POST request.
Prepare runs after Init before request function execution.
Put adds a request function to handle PUT request.
Redirect sends the redirection response to url with status code.
Render sends the response with rendered template bytes as text/html type.
RenderBytes returns the bytes of rendered template string. Do not send out response.
RenderString returns the rendered template string. Do not send out response.
SaveToFile saves uploaded file to new path. it only operates the first one of mutil-upload form file field.
ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
ServeJSON sends a json response with encoding charset.
ServeJSONP sends a jsonp response.
ServeXML sends xml response.
ServeYAML sends yaml response.
SessionRegenerateID regenerates session id for this session. the session data have no changes.
SetData set the data depending on the accepted
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{})
SetSecureCookie puts value into cookie after encoded the value.
func (c *Controller) SetSession(name interface{}, value interface{})
SetSession puts value into session.
StartSession starts session and load old session data info this controller.
StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
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]).
URLFor does another controller handler in this request function. it goes to this controller method if endpoint is not clear.
URLMapping register the internal Controller router.
XSRFFormHTML writes an input field contains xsrf token value.
XSRFToken creates a CSRF token string and returns.
type ControllerComments struct { }
ControllerComments store the comment for the controller method
ControllerCommentsSlice implements the sort interface
ControllerFilter store the filter for controller
type ControllerFilterComments struct { }
ControllerFilterComments store the comment for controller level filter
type ControllerImportComments struct { }
ControllerImportComments store the import comment for controller needed
type ControllerInfo struct { }
ControllerInfo holds information about the controller.
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 struct { }
ControllerRegister containers registered router rules, controller handlers and filters.
NewControllerRegister returns a new ControllerRegister.
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")
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.
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.
AddMethod add http method router usage:
AddMethod("get","/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Any add all method usage:
Any("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Delete add delete method usage:
Delete("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
FindPolicy Find Router info for URL
FindRouter Find Router info for URL
Get add get method usage:
Get("/", func(ctx *context.Context){ ctx.Output.Body("hello world") })
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)
GiveBackContext put the ctx into pool so that it could be reuse
func (*ControllerRegister) Handler ¶ added in v1.6.0Handler add user defined Handler
Head add head method usage:
Head("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Include only when the Runmode is dev will generate router file in the router/auto.go from the controller Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
InsertFilter Add a FilterFunc with pattern rule and action constant. params is for:
Options add options method usage:
Options("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Patch add patch method usage:
Patch("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Post add post method usage:
Post("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Put add put method usage:
Put("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
Implement http.Handler interface.
URLFor does another controller handler in this request function. it can access any controller method.
type FileSystem struct { }
FilterFunc defines a filter function which is invoked before the controller handler is executed.
type FilterHandler ¶ added in v1.4.2FilterHandler is an interface for
var ( 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 FilterHandler = &logFilter{} )
type FilterRouter struct { }
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.
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.
FlashData is a tools to maintain data when using across request.
NewFlash return a new empty FlashData struct.
ReadFromRequest parsed flash data from encoded values in cookie.
Error writes error message to flash.
Notice writes notice message to flash.
Store does the saving operation of flash data. the data are encoded and saved in cookie.
Success writes success message to flash.
Warning writes warning message to flash.
LinkNamespace used as link action
NSAfter add Namespace FinishRouter filter
NSAutoPrefix call Namespace AutoPrefix
NSAutoRouter call Namespace AutoRouter
NSBefore Namespace BeforeRouter filter
NSCond is Namespace Condition
NSDelete call Namespace Delete
func NSHandler ¶ added in v1.6.1NSHandler add handler
NSHead call Namespace Head
NSInclude Namespace Include ControllerInterface
NSNamespace add sub Namespace
NSOptions call Namespace Options
NSPatch call Namespace Patch
NSPost call Namespace Post
NSRouter call Namespace Router
Listen holds for http and https related config
LogConfig holds Log related config
M is Map shortcut
PrintTree prints all registered routers.
MiddleWare function for http.Handler
type Namespace struct { }
Namespace is store all the info
NewNamespace get new Namespace
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
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") } })
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")) }),
)
PolicyFunc defines a policy function which is invoked before the controller handler is executed.
type SessionConfig struct { SessionOn bool SessionProvider string SessionName string SessionGCMaxLifetime int64 SessionProviderConfig string SessionCookieLifeTime int SessionAutoSetCookie bool SessionDomain string SessionDisableHTTPOnly bool SessionEnableSidInURLQuery bool SessionCookieSameSite http.SameSite }
SessionConfig holds session related config
Tree has three elements: FixRouter/wildcard/leaves fixRouter stores Fixed Router wildcard stores params leaves store the endpoint information
NewTree return a new Tree
func (t *Tree) AddRouter(pattern string, runObject interface{})
AddRouter call addseg function
AddTree will add tree to the exist Tree prefix should has no params
Match router to runObject & params
WebConfig holds web related config
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4