Documentation ¶
Overview ¶
beego is an open-source, high-performance, modularity, full-stack web framework
package main
import "github.com/astaxie/beego"
func main() { beego.Run() }
more infomation: http://beego.me
Index ¶
- Constants
- Variables
- func AddAPPStartHook(hf hookfunc)
- func AddFuncMap(key string, funname interface{}) error
- func AddNamespace(nl ...*Namespace)
- func AddTemplateExt(ext string)
- func Alert(v ...interface{})
- func AssetsCss(src string) template.HTML
- func AssetsJs(src string) template.HTML
- func BuildTemplate(dir string) error
- func Compare(a, b interface{}) (equal bool)
- func CompareNot(a, b interface{}) (equal bool)
- func Config(returnType, key string, defaultVal interface{}) (value interface{}, err error)
- 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 HasTemplateExt(paths string) bool
- func Html2str(html string) string
- func Htmlquote(src string) string
- func Htmlunquote(src string) string
- func Info(v ...interface{})deprecated
- func Informational(v ...interface{})
- func NSAfter(filiterList ...FilterFunc) innnerNamespace
- func NSAny(rootpath string, f FilterFunc) innnerNamespace
- func NSAutoPrefix(prefix string, c ControllerInterface) innnerNamespace
- func NSAutoRouter(c ControllerInterface) innnerNamespace
- func NSBefore(filiterList ...FilterFunc) innnerNamespace
- func NSCond(cond namespaceCond) innnerNamespace
- func NSDelete(rootpath string, f FilterFunc) innnerNamespace
- func NSGet(rootpath string, f FilterFunc) innnerNamespace
- func NSHead(rootpath string, f FilterFunc) innnerNamespace
- func NSInclude(cList ...ControllerInterface) innnerNamespace
- func NSNamespace(prefix string, params ...innnerNamespace) innnerNamespace
- func NSOptions(rootpath string, f FilterFunc) innnerNamespace
- func NSPatch(rootpath string, f FilterFunc) innnerNamespace
- func NSPost(rootpath string, f FilterFunc) innnerNamespace
- func NSPut(rootpath string, f FilterFunc) innnerNamespace
- func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) innnerNamespace
- func NotNil(a interface{}) (is_nil bool)
- func Notice(v ...interface{})
- func ParseConfig() (err error)
- func ParseForm(form url.Values, obj interface{}) error
- func RenderForm(obj interface{}) template.HTML
- func Run(params ...string)
- func SetLevel(l int)
- func SetLogFuncCall(b bool)
- func SetLogger(adaptername string, config string) error
- func Str2html(raw string) template.HTML
- func Substr(s string, start, length int) string
- func TestBeegoInit(apppath string)
- func Trace(v ...interface{})
- func UrlFor(endpoint string, values ...interface{}) string
- func Warn(v ...interface{})deprecated
- func Warning(v ...interface{})
- type 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
- 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() (controllerName, actionName string)
- func (c *Controller) GetFile(key string) (multipart.File, *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) 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()
- func (c *Controller) ServeJson(encoding ...bool)
- func (c *Controller) ServeJsonp()
- func (c *Controller) ServeXml()
- func (c *Controller) SessionRegenerateID()
- func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{})
- func (c *Controller) SetSession(name interface{}, value interface{})
- func (c *Controller) StartSession() session.SessionStore
- func (c *Controller) StopRun()
- func (c *Controller) URLMapping()
- func (c *Controller) UrlFor(endpoint string, values ...interface{}) string
- func (c *Controller) XsrfFormHtml() string
- func (c *Controller) XsrfToken() string
- type ControllerComments
- type ControllerInterface
- type ControllerRegistor
- func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingMethods ...string)
- func (p *ControllerRegistor) AddAuto(c ControllerInterface)
- func (p *ControllerRegistor) AddAutoPrefix(prefix string, c ControllerInterface)
- func (p *ControllerRegistor) AddMethod(method, pattern string, f FilterFunc)
- func (p *ControllerRegistor) Any(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Delete(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Get(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Handler(pattern string, h http.Handler, options ...interface{})
- func (p *ControllerRegistor) Head(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Include(cList ...ControllerInterface)
- func (p *ControllerRegistor) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error
- func (p *ControllerRegistor) Options(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Patch(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Post(pattern string, f FilterFunc)
- func (p *ControllerRegistor) Put(pattern string, f FilterFunc)
- func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
- func (p *ControllerRegistor) UrlFor(endpoint string, values ...interface{}) string
- 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 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 Tree
Constants ¶
const ( LevelEmergency = iota LevelAlert LevelCritical LevelError LevelWarning LevelNotice LevelInformational LevelDebug )
Log levels to control the logging output.
const ( // default filter execution points BeforeStatic = iota BeforeRouter BeforeExec AfterExec FinishRouter )
const COMMENTFL = "commentsRouter_"
const VERSION = "1.4.3"
beego web framework version.
Variables ¶
var ( BeeApp *App // beego application AppName string AppPath string AppConfigPath string StaticDir map[string]string TemplateCache map[string]*template.Template // template caching map StaticExtensionsToGzip []string // files with should be compressed with gzip (.js,.css,etc) EnableHttpListen bool HttpAddr string HttpPort int ListenTCP4 bool EnableHttpTLS bool HttpsPort int HttpCertFile string HttpKeyFile string RecoverPanic bool // flag of auto recover panic AutoRender bool // flag of render template automatically ViewsPath string AppConfig *beegoAppConfig RunMode string // run mode, "dev" or "prod" GlobalSessions *session.Manager // global session mananger SessionOn bool // flag of starting session auto. default is false. SessionProvider string // default session provider, memory, mysql , redis ,etc. SessionName string // the cookie name when saving session id into cookie. SessionGCMaxLifetime int64 // session gc time for auto cleaning expired session. SessionSavePath string // if use mysql/redis/file provider, define save path to connection info. SessionCookieLifeTime int // the life time of session id in cookie. SessionAutoSetCookie bool // auto setcookie SessionDomain string // the cookie domain default is empty UseFcgi bool UseStdIo bool MaxMemory int64 EnableGzip bool // flag of enable gzip DirectoryIndex bool // flag of display directory index. default is false. HttpServerTimeOut int64 ErrorsShow bool // flag of show errors in page. if true, show error and trace info in page rendered with error template. XSRFKEY string // xsrf hash salt string. EnableXSRF bool // flag of enable xsrf. XSRFExpire int // the expiry of xsrf value. CopyRequestBody bool // flag of copy raw request body in context. TemplateLeft string TemplateRight string BeegoServerName string // beego server name exported in response header. EnableAdmin bool // flag of enable admin module to log every request info. AdminHttpAddr string // http server configurations for admin module. AdminHttpPort int FlashName string // name of the flash variable found in response header and cookie FlashSeperator string // used to seperate flash key:value AppConfigProvider string // config provider EnableDocs bool // enable generate docs & server docs API Swagger RouterCaseSensitive bool // router case sensitive default is true AccessLogs bool // print access logs, default is false )
var ( // custom error when user stop request handler manually. USERSTOPRUN = errors.New("User stop run") GlobalControllerRouter map[string][]ControllerComments = make(map[string][]ControllerComments) //pkgpath+controller:comments )
var ( // beego template caching map and supported template file extensions. BeeTemplates map[string]*template.Template BeeTemplateExt []string )
var BeeLogger *logs.BeeLogger
logger references the used application logger.
var ErrorMaps map[string]*errorInfo
map of http handlers for each error string.
FilterMonitorFunc is default monitor filter when admin module is enable. if this func returns, admin module records qbs for this request by condition of this function logic. usage:
func MyFilterMonitor(method, requestPath string, t time.Duration) bool { if method == "POST" { return false } if t.Nanoseconds() < 100 { return false } if strings.HasPrefix(requestPath, "/astaxie") { return false } return true } beego.FilterMonitorFunc = MyFilterMonitor.
var GlobalDocApi map[string]interface{}
Functions ¶
func AddAPPStartHook ¶
func AddAPPStartHook(hf hookfunc)
The hookfunc will run in beego.Run() such as sessionInit, middlerware start, buildtemplate, admin start
func AddFuncMap ¶
AddFuncMap let user to register a func in the template.
func AddNamespace ¶
func AddNamespace(nl ...*Namespace)
register Namespace into beego.Handler support multi Namespace
func BuildTemplate ¶
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)
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 ExceptMethodAppend ¶
func ExceptMethodAppend(action string)
To append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
func HasTemplateExt ¶
return this path contains supported template extension of beego or not.
func Info
deprecated
func Info(v ...interface{})
Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
func Informational ¶ added in v1.4.0
func Informational(v ...interface{})
Info logs a message at info level.
func NSAfter ¶ added in v1.3.0
func NSAfter(filiterList ...FilterFunc) innnerNamespace
Namespace FinishRouter filter
func NSAny ¶ added in v1.3.0
func NSAny(rootpath string, f FilterFunc) innnerNamespace
Namespace Any
func NSAutoPrefix ¶ added in v1.3.0
func NSAutoPrefix(prefix string, c ControllerInterface) innnerNamespace
Namespace AutoPrefix
func NSAutoRouter ¶ added in v1.3.0
func NSAutoRouter(c ControllerInterface) innnerNamespace
Namespace AutoRouter
func NSBefore ¶ added in v1.3.0
func NSBefore(filiterList ...FilterFunc) innnerNamespace
Namespace BeforeRouter filter
func NSDelete ¶ added in v1.3.0
func NSDelete(rootpath string, f FilterFunc) innnerNamespace
Namespace Delete
func NSGet ¶ added in v1.3.0
func NSGet(rootpath string, f FilterFunc) innnerNamespace
Namespace Get
func NSHead ¶ added in v1.3.0
func NSHead(rootpath string, f FilterFunc) innnerNamespace
Namespace Head
func NSInclude ¶ added in v1.3.0
func NSInclude(cList ...ControllerInterface) innnerNamespace
Namespace Include ControllerInterface
func NSNamespace ¶ added in v1.3.0
func NSNamespace(prefix string, params ...innnerNamespace) innnerNamespace
Namespace add sub Namespace
func NSOptions ¶ added in v1.3.0
func NSOptions(rootpath string, f FilterFunc) innnerNamespace
Namespace Options
func NSPatch ¶ added in v1.3.0
func NSPatch(rootpath string, f FilterFunc) innnerNamespace
Namespace Patch
func NSPost ¶ added in v1.3.0
func NSPost(rootpath string, f FilterFunc) innnerNamespace
Namespace Post
func NSPut ¶ added in v1.3.0
func NSPut(rootpath string, f FilterFunc) innnerNamespace
Namespace Put
func NSRouter ¶ added in v1.3.0
func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) innnerNamespace
Namespace Router
func ParseConfig ¶
func ParseConfig() (err error)
ParseConfig parsed default config file. now only support ini, next will support json.
func RenderForm ¶
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(":8089") beego.Run("127.0.0.1:8089")
func SetLevel ¶
func SetLevel(l int)
SetLogLevel sets the global log level used by the simple logger.
func SetLogFuncCall ¶
func SetLogFuncCall(b bool)
func Trace ¶
func Trace(v ...interface{})
Trace logs a message at trace level. Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
func UrlFor ¶
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 Warn
deprecated
func Warn(v ...interface{})
Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
Types ¶
type App ¶
type App struct { Handlers *ControllerRegistor Server *http.Server }
App defines beego application with a new PatternServeMux.
func Any ¶
func Any(rootpath string, f FilterFunc) *App
register router for all method 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
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.ErrorHandler(&controllers.ErrorController{})
func Errorhandler ¶
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
register router for Get method usage:
beego.Get("/", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Handler ¶
register router for own Handler usage:
beego.Handler("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func Head ¶
func Head(rootpath string, f FilterFunc) *App
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
Router add list from 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
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
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
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
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.
type Controller ¶
type Controller struct { Ctx *context.Context Data map[interface{}]interface{} TplNames string Layout string LayoutSections map[string]string // the key is the section name and the value is the template name TplExt string CruSession session.SessionStore XSRFExpire int AppController interface{} EnableRender bool EnableXSRF bool // 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)
Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
func (*Controller) CheckXsrfCookie ¶
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{})
SetSession 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() (controllerName, actionName 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) 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) HandlerFunc ¶ added in v1.3.0
func (c *Controller) HandlerFunc(fnname string) bool
call function fn
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())
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()
ServeFormatted serve Xml OR Json, depending on the value of the Accept header
func (*Controller) ServeJson ¶
func (c *Controller) ServeJson(encoding ...bool)
ServeJson sends a json response with encoding charset.
func (*Controller) ServeJsonp ¶
func (c *Controller) ServeJsonp()
ServeJsonp sends a jsonp response.
func (*Controller) SessionRegenerateID ¶
func (c *Controller) SessionRegenerateID()
SessionRegenerateID regenerates session id for this session. the session data have no changes.
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.SessionStore
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) URLMapping ¶ added in v1.3.0
func (c *Controller) URLMapping()
URLMapping register the internal Controller router.
func (*Controller) UrlFor ¶
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) XsrfFormHtml ¶
func (c *Controller) XsrfFormHtml() string
XsrfFormHtml writes an input field contains xsrf token value.
func (*Controller) XsrfToken ¶
func (c *Controller) XsrfToken() string
XsrfToken creates a xsrf token string and returns.
type ControllerComments ¶ added in v1.3.0
type ControllerComments struct { Method string Router string AllowHTTPMethods []string Params []map[string]string }
store the comment for the controller method
type ControllerInterface ¶
type ControllerInterface interface { Init(ct *context.Context, controllerName, actionName string, app interface{}) Prepare() Get() Post() Delete() Put() Head() Patch() Options() Finish() Render() error XsrfToken() string CheckXsrfCookie() bool HandlerFunc(fn string) bool URLMapping() }
ControllerInterface is an interface to uniform all controller handler.
type ControllerRegistor ¶
type ControllerRegistor struct {
// contains filtered or unexported fields
}
ControllerRegistor containers registered router rules, controller handlers and filters.
func NewControllerRegister ¶ added in v1.3.0
func NewControllerRegister() *ControllerRegistor
NewControllerRegister returns a new ControllerRegistor.
func (*ControllerRegistor) Add ¶
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingMethods ...string)
Add controller handler and pattern rules to ControllerRegistor. 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 (*ControllerRegistor) AddAuto ¶
func (p *ControllerRegistor) AddAuto(c ControllerInterface)
Add auto router to ControllerRegistor. 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 (*ControllerRegistor) AddAutoPrefix ¶
func (p *ControllerRegistor) AddAutoPrefix(prefix string, c ControllerInterface)
Add auto router to ControllerRegistor 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 (*ControllerRegistor) AddMethod ¶
func (p *ControllerRegistor) AddMethod(method, pattern string, f FilterFunc)
add http method router usage:
AddMethod("get","/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Any ¶
func (p *ControllerRegistor) Any(pattern string, f FilterFunc)
add all method usage:
Any("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Delete ¶
func (p *ControllerRegistor) Delete(pattern string, f FilterFunc)
add delete method usage:
Delete("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Get ¶
func (p *ControllerRegistor) Get(pattern string, f FilterFunc)
add get method usage:
Get("/", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Handler ¶
func (p *ControllerRegistor) Handler(pattern string, h http.Handler, options ...interface{})
add user defined Handler
func (*ControllerRegistor) Head ¶
func (p *ControllerRegistor) Head(pattern string, f FilterFunc)
add head method usage:
Head("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Include ¶ added in v1.3.0
func (p *ControllerRegistor) Include(cList ...ControllerInterface)
only when the Runmode is dev will generate router file in the router/auto.go from the controller Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
func (*ControllerRegistor) InsertFilter ¶
func (p *ControllerRegistor) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error
Add a FilterFunc with pattern rule and action constant. The bool params is for setting the returnOnOutput value (false allows multiple filters to execute)
func (*ControllerRegistor) Options ¶
func (p *ControllerRegistor) Options(pattern string, f FilterFunc)
add options method usage:
Options("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Patch ¶
func (p *ControllerRegistor) Patch(pattern string, f FilterFunc)
add patch method usage:
Patch("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Post ¶
func (p *ControllerRegistor) Post(pattern string, f FilterFunc)
add post method usage:
Post("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) Put ¶
func (p *ControllerRegistor) Put(pattern string, f FilterFunc)
add put method usage:
Put("/api/:id", func(ctx *context.Context){ ctx.Output.Body("hello world") })
func (*ControllerRegistor) ServeHTTP ¶
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
Implement http.Handler interface.
func (*ControllerRegistor) UrlFor ¶
func (p *ControllerRegistor) UrlFor(endpoint string, values ...interface{}) string
UrlFor does another controller handler in this request function. it can access any controller method.
type FilterHandler ¶ added in v1.4.2
type FilterHandler interface {
Filter(*beecontext.Context) bool
}
var ( // supported http methods. HTTPMETHOD = map[string]string{ "GET": "GET", "POST": "POST", "PUT": "PUT", "DELETE": "DELETE", "PATCH": "PATCH", "OPTIONS": "OPTIONS", "HEAD": "HEAD", "TRACE": "TRACE", "CONNECT": "CONNECT", } DefaultLogFilter FilterHandler = &logFilter{} )
type FilterRouter ¶
type FilterRouter struct {
// contains filtered or unexported fields
}
FilterRouter defines filter operation before controller handler execution. it can match patterned url and do filter function when action arrives.
func (*FilterRouter) ValidRouter ¶
func (f *FilterRouter) ValidRouter(router string) (bool, map[string]string)
ValidRouter check current request is valid for this filter. if matched, returns parsed params in this request by defined filter router pattern.
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 Namespace ¶
type Namespace struct {
// contains filtered or unexported fields
}
Namespace is store all the info
func NewNamespace ¶
get new Namespace
func (*Namespace) Any ¶
func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace
same as beego.Any refer: https://godoc.org/github.com/astaxie/beego#Any
func (*Namespace) AutoPrefix ¶
func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace
same as beego.AutoPrefix refer: https://godoc.org/github.com/astaxie/beego#AutoPrefix
func (*Namespace) AutoRouter ¶
func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace
same as beego.AutoRouter refer: https://godoc.org/github.com/astaxie/beego#AutoRouter
func (*Namespace) Cond ¶
set condtion 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
same as beego.Delete refer: https://godoc.org/github.com/astaxie/beego#Delete
func (*Namespace) Filter ¶
func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace
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
same as beego.Get refer: https://godoc.org/github.com/astaxie/beego#Get
func (*Namespace) Handler ¶
same as beego.Handler refer: https://godoc.org/github.com/astaxie/beego#Handler
func (*Namespace) Head ¶
func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace
same as beego.Head refer: https://godoc.org/github.com/astaxie/beego#Head
func (*Namespace) Include ¶ added in v1.3.0
func (n *Namespace) Include(cList ...ControllerInterface) *Namespace
add include class refer: https://godoc.org/github.com/astaxie/beego#Include
func (*Namespace) Namespace ¶
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
same as beego.Options refer: https://godoc.org/github.com/astaxie/beego#Options
func (*Namespace) Patch ¶
func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace
same as beego.Patch refer: https://godoc.org/github.com/astaxie/beego#Patch
func (*Namespace) Post ¶
func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace
same as beego.Post refer: https://godoc.org/github.com/astaxie/beego#Post
func (*Namespace) Put ¶
func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace
same as beego.Put refer: https://godoc.org/github.com/astaxie/beego#Put
func (*Namespace) Router ¶
func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace
same as beego.Rourer refer: https://godoc.org/github.com/astaxie/beego#Router
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Usage: import( "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("memory", `{"interval":60}`) Use it like this: bm.Put("astaxie", 1, 10) bm.Get("astaxie") bm.IsExist("astaxie") bm.Delete("astaxie") more docs http://beego.me/docs/module/cache.md
|
Usage: import( "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("memory", `{"interval":60}`) Use it like this: bm.Put("astaxie", 1, 10) bm.Get("astaxie") bm.IsExist("astaxie") bm.Delete("astaxie") more docs http://beego.me/docs/module/cache.md |
memcache
package memcahe for cache provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/astaxie/beego/cache/memcache" "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`) more docs http://beego.me/docs/module/cache.md
|
package memcahe for cache provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/astaxie/beego/cache/memcache" "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`) more docs http://beego.me/docs/module/cache.md |
redis
package redis for cache provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/astaxie/beego/cache/redis" "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`) more docs http://beego.me/docs/module/cache.md
|
package redis for cache provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/astaxie/beego/cache/redis" "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`) more docs http://beego.me/docs/module/cache.md |
Usage: import( "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("ini", "config.conf") cnf APIS: cnf.Set(key, val string) error cnf.String(key string) string cnf.Strings(key string) []string cnf.Int(key string) (int, error) cnf.Int64(key string) (int64, error) cnf.Bool(key string) (bool, error) cnf.Float(key string) (float64, error) cnf.DefaultString(key string, defaultval string) string cnf.DefaultStrings(key string, defaultval []string) []string cnf.DefaultInt(key string, defaultval int) int cnf.DefaultInt64(key string, defaultval int64) int64 cnf.DefaultBool(key string, defaultval bool) bool cnf.DefaultFloat(key string, defaultval float64) float64 cnf.DIY(key string) (interface{}, error) cnf.GetSection(section string) (map[string]string, error) cnf.SaveConfigFile(filename string) error more docs http://beego.me/docs/module/config.md
|
Usage: import( "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("ini", "config.conf") cnf APIS: cnf.Set(key, val string) error cnf.String(key string) string cnf.Strings(key string) []string cnf.Int(key string) (int, error) cnf.Int64(key string) (int64, error) cnf.Bool(key string) (bool, error) cnf.Float(key string) (float64, error) cnf.DefaultString(key string, defaultval string) string cnf.DefaultStrings(key string, defaultval []string) []string cnf.DefaultInt(key string, defaultval int) int cnf.DefaultInt64(key string, defaultval int64) int64 cnf.DefaultBool(key string, defaultval bool) bool cnf.DefaultFloat(key string, defaultval float64) float64 cnf.DIY(key string) (interface{}, error) cnf.GetSection(section string) (map[string]string, error) cnf.SaveConfigFile(filename string) error more docs http://beego.me/docs/module/config.md |
xml
package xml for config provider depend on github.com/beego/x2j go install github.com/beego/x2j Usage: import( _ "github.com/astaxie/beego/config/xml" "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("xml", "config.xml") more docs http://beego.me/docs/module/config.md
|
package xml for config provider depend on github.com/beego/x2j go install github.com/beego/x2j Usage: import( _ "github.com/astaxie/beego/config/xml" "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("xml", "config.xml") more docs http://beego.me/docs/module/config.md |
yaml
package yaml for config provider depend on github.com/beego/goyaml2 go install github.com/beego/goyaml2 Usage: import( _ "github.com/astaxie/beego/config/yaml" "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.md
|
package yaml for config provider depend on github.com/beego/goyaml2 go install github.com/beego/goyaml2 Usage: import( _ "github.com/astaxie/beego/config/yaml" "github.com/astaxie/beego/config" ) cnf, err := config.NewConfig("yaml", "config.yaml") more docs http://beego.me/docs/module/config.md |
Usage: import "github.com/astaxie/beego/context" ctx := context.Context{Request:req,ResponseWriter:rw} more docs http://beego.me/docs/module/context.md
|
Usage: import "github.com/astaxie/beego/context" ctx := context.Context{Request:req,ResponseWriter:rw} more docs http://beego.me/docs/module/context.md |
example
|
|
chat
Beego (http://beego.me/) @description beego is an open-source, high-performance web framework for the Go programming language.
|
Beego (http://beego.me/) @description beego is an open-source, high-performance web framework for the Go programming language. |
Usage: import "github.com/astaxie/beego/httplib" b := httplib.Post("http://beego.me/") b.Param("username","astaxie") b.Param("password","123456") b.PostFile("uploadfile1", "httplib.pdf") b.PostFile("uploadfile2", "httplib.txt") str, err := b.String() if err != nil { t.Fatal(err) } fmt.Println(str) more docs http://beego.me/docs/module/httplib.md
|
Usage: import "github.com/astaxie/beego/httplib" b := httplib.Post("http://beego.me/") b.Param("username","astaxie") b.Param("password","123456") b.PostFile("uploadfile1", "httplib.pdf") b.PostFile("uploadfile2", "httplib.txt") str, err := b.String() if err != nil { t.Fatal(err) } fmt.Println(str) more docs http://beego.me/docs/module/httplib.md |
Usage: import "github.com/astaxie/beego/logs" log := NewLogger(10000) log.SetLogger("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://beego.me/docs/module/logs.md
|
Usage: import "github.com/astaxie/beego/logs" log := NewLogger(10000) log.SetLogger("console", "") > the first params stand for how many channel Use it like this: log.Trace("trace") log.Info("info") log.Warn("warning") log.Debug("debug") log.Critical("critical") more docs http://beego.me/docs/module/logs.md |
Usage: import "github.com/astaxie/beego/middleware" I18N = middleware.NewLocale("conf/i18n.conf", beego.AppConfig.String("language")) more docs: http://beego.me/docs/module/i18n.md
|
Usage: import "github.com/astaxie/beego/middleware" I18N = middleware.NewLocale("conf/i18n.conf", beego.AppConfig.String("language")) more docs: http://beego.me/docs/module/i18n.md |
migration package for migration The table structure is as follow: CREATE TABLE `migrations` ( `id_migration` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key', `name` varchar(255) DEFAULT NULL COMMENT 'migration name, unique', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back', `statements` longtext COMMENT 'SQL statements for this migration', `rollback_statements` longtext, `status` enum('update','rollback') DEFAULT NULL COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back', PRIMARY KEY (`id_migration`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
migration package for migration The table structure is as follow: CREATE TABLE `migrations` ( `id_migration` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key', `name` varchar(255) DEFAULT NULL COMMENT 'migration name, unique', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back', `statements` longtext COMMENT 'SQL statements for this migration', `rollback_statements` longtext, `status` enum('update','rollback') DEFAULT NULL COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back', PRIMARY KEY (`id_migration`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
Simple Usage package main import ( "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" // import your used driver ) // Model Struct type User struct { Id int `orm:"auto"` Name string `orm:"size(100)"` } func init() { orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30) } func main() { o := orm.NewOrm() user := User{Name: "slene"} // insert id, err := o.Insert(&user) // update user.Name = "astaxie" num, err := o.Update(&user) // read one u := User{Id: user.Id} err = o.Read(&u) // delete num, err = o.Delete(&u) } more docs: http://beego.me/docs/mvc/model/overview.md
|
Simple Usage package main import ( "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" // import your used driver ) // Model Struct type User struct { Id int `orm:"auto"` Name string `orm:"size(100)"` } func init() { orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30) } func main() { o := orm.NewOrm() user := User{Name: "slene"} // insert id, err := o.Insert(&user) // update user.Name = "astaxie" num, err := o.Update(&user) // read one u := User{Id: user.Id} err = o.Read(&u) // delete num, err = o.Delete(&u) } more docs: http://beego.me/docs/mvc/model/overview.md |
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. |
cors
Package cors provides handlers to enable CORS support.
|
Package cors provides handlers to enable CORS support. |
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, "sessionIDHashFunc": "sha1", "sessionIDHashKey": "", "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
|
package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "sessionIDHashFunc": "sha1", "sessionIDHashKey": "", "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md |
couchbase
package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/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 |
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
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
|
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 |
swagger struct definition
|
swagger struct definition |
toolbox healthcheck type DatabaseCheck struct { } func (dc *DatabaseCheck) Check() error { if dc.isConnected() { return nil } else { return errors.New("can't connect database") } } AddHealthCheck("database",&DatabaseCheck{}) more docs: http://beego.me/docs/module/toolbox.md
|
toolbox healthcheck type DatabaseCheck struct { } func (dc *DatabaseCheck) Check() error { if dc.isConnected() { return nil } else { return errors.New("can't connect database") } } AddHealthCheck("database",&DatabaseCheck{}) more docs: http://beego.me/docs/module/toolbox.md |
captcha
an example for use captcha “` package controllers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/cache" "github.com/astaxie/beego/utils/captcha" ) var cpt *captcha.Captcha func init() { // use beego cache system store the captcha data store := cache.NewMemoryCache() cpt = captcha.NewWithFilter("/captcha/", store) } type MainController struct { beego.Controller } func (this *MainController) Get() { this.TplNames = "index.tpl" } func (this *MainController) Post() { this.TplNames = "index.tpl" this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request) } “` template usage “` {{.Success}} <form action="/" method="post"> {{create_captcha}} <input name="captcha" type="text"> </form> “`
|
an example for use captcha “` package controllers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/cache" "github.com/astaxie/beego/utils/captcha" ) var cpt *captcha.Captcha func init() { // use beego cache system store the captcha data store := cache.NewMemoryCache() cpt = captcha.NewWithFilter("/captcha/", store) } type MainController struct { beego.Controller } func (this *MainController) Get() { this.TplNames = "index.tpl" } func (this *MainController) Post() { this.TplNames = "index.tpl" this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request) } “` template usage “` {{.Success}} <form action="/" method="post"> {{create_captcha}} <input name="captcha" type="text"> </form> “` |
pagination
The pagination package provides utilities to setup a paginator within the context of a http request.
|
The pagination package provides utilities to setup a paginator within the context of a http request. |
package for validations import ( "github.com/astaxie/beego/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } more info: http://beego.me/docs/mvc/controller/validation.md
|
package for validations import ( "github.com/astaxie/beego/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } more info: http://beego.me/docs/mvc/controller/validation.md |