modulepackage
1.12.5-sonek
Repository: https://github.com/openstars/beego.git
Documentation: pkg.go.dev
# README
Beego

beego is used for rapid development of RESTful APIs, web apps and backend services in Go. It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific features such as interfaces and struct embedding.
More info at beego.me.
Quick Start
Download and install
go get github.com/OpenStars/beego
Create file hello.go
package main
import "github.com/OpenStars/beego"
func main(){
beego.Run()
}
Build and run
go build hello.go
./hello
Go to http://localhost:8080
Congratulations! You've just built your first beego app.
Please see Documentation for more.
Features
- RESTful support
- MVC architecture
- Modularity
- Auto API documents
- Annotation router
- Namespace
- Powerful development tools
- Full stack for Web & API
Documentation
Community
- http://beego.me/community
- Welcome to join us in Slack: https://beego.slack.com, you can get invited from here
- QQ Group Group ID:523992905
License
beego source code is licensed under the Apache Licence, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).
# Packages
Package cache provide a Cache interface and some implement engine Usage:
import( "github.com/OpenStars/beego/cache" )
bm, err := cache.NewCache("memory", `{"interval":60}`)
Use it like this:
bm.Put("astaxie", 1, 10 * time.Second) bm.Get("astaxie") bm.IsExist("astaxie") bm.Delete("astaxie")
more docs http://beego.me/docs/module/cache.md.
Package config is used to parse config.
Package context provide the context utils Usage:
import "github.com/OpenStars/beego/context"
ctx := context.Context{Request:req,ResponseWriter:rw}
more docs http://beego.me/docs/module/context.md.
Package grace use to hot reload Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
Usage:
import( "log" "net/http" "os"
"github.com/OpenStars/beego/grace" )
func handler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("WORLD!")) }
func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", handler)
err := grace.ListenAndServe("localhost:8080", mux) if err != nil { log.Println(err) } log.Println("Server on 8080 stopped") os.Exit(0) }.
Package httplib is used as http.Client Usage:
import "github.com/OpenStars/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.
Package logs provide a general log interface Usage:
import "github.com/OpenStars/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.
Package migration is used 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;.
Package orm provide ORM for MySQL/PostgreSQL/sqlite Simple Usage
package main
import ( "fmt" "github.com/OpenStars/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.
No description provided by the author
Package session provider
Usage: import( "github.com/OpenStars/beego/session" )
func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() }
more docs: http://beego.me/docs/module/session.md.
Package swagger struct definition.
No description provided by the author
Package 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.
No description provided by the author
Package validation for validations
import ( "github.com/OpenStars/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, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } }
more info: http://beego.me/docs/mvc/controller/validation.md.
# Functions
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.
AddTemplateEngine add a new templatePreProcessor which support extension.
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 folderwill panic if called after beego.Run().
Alert logs a message at alert level.
Any used to register router for all methods usage: beego.Any("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
AssetsCSS returns stylesheet link tag with src string.
AssetsJs returns script tag with src string.
AutoPrefix adds controller handler to BeeApp with prefix.
AutoRouter adds defined controller handler to BeeApp.
BuildTemplate will build all template files in a directory.
Compare is a quick and dirty comparison function.
CompareNot !Compare.
Critical logs a message at critical level.
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.
DateParse Parse Date use PHP time format.
Debug logs a message at debug level.
Delete used to register router for Delete method usage: beego.Delete("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
DelStaticPath removes the static folder setting in this url pattern in beego application.
Emergency logs a message at emergency level.
Error logs a message at error level.
ErrorController registers ControllerInterface to each http err code string.
ErrorHandler registers http.HandlerFunc to each http err code string.
Exception Write HttpStatus with errCode and Exec error handler if exist.
ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter.
ExecuteTemplate applies the template with name to the specified data object, writing the output to wr.
ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object, writing the output to wr.
Get used to register router for Get method usage: beego.Get("/", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
GetConfig get the Appconfig.
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)) })).
HasTemplateExt return this path contains supported template extension of beego or not.
Head used to register router for Head method usage: beego.Head("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
HTML2str returns escaping text convert from html.
Htmlquote returns quoted html string.
Htmlunquote returns unquoted html string.
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 *].
Info compatibility alias for Warning() Deprecated: use github.com/OpenStars/beego/logs instead.
Informational logs a message at info level.
InitBeegoBeforeTest is for test package init.
InsertFilter adds a FilterFunc with pattern condition and action constant.
LoadAppConfig allow developer to apply a config file.
LogAccess logging info HTTP Access.
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.
NewApp returns a new beego application.
NewControllerRegister returns a new ControllerRegister.
NewFlash return a new empty FlashData struct.
NewNamespace get new Namespace.
NewTree return a new Tree.
Notice logs a message at notice level.
NotNil the same as CompareNot.
NSAfter add Namespace FinishRouter filter.
NSAny call Namespace Any.
NSAutoPrefix call Namespace AutoPrefix.
NSAutoRouter call Namespace AutoRouter.
NSBefore Namespace BeforeRouter filter.
NSCond is Namespace Condition.
NSDelete call Namespace Delete.
NSGet call Namespace Get.
NSHandler 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.
NSPut call Namespace Put.
NSRouter call Namespace Router.
Options used to register router for Options method usage: beego.Options("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
ParseForm will parse form values to struct via tag.
Patch used to register router for Patch method usage: beego.Patch("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
Policy Register new policy in beego.
Post used to register router for Post method usage: beego.Post("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
PrintTree prints all registered routers.
Put used to register router for Put method usage: beego.Put("/api", func(ctx *context.Context){ ctx.Output.Body("hello world") }).
ReadFromRequest parsed flash data from encoded values in cookie.
RenderForm will render object to form html.
RESTRouter adds a restful controller handler to BeeApp.
Router adds a patterned controller handler to BeeApp.
Run beego application.
RunWithMiddleWares Run beego application with middlewares.
SetLevel sets the global log level used by the simple logger.
SetLogFuncCall set the CallDepth, default is 3 Deprecated: use github.com/OpenStars/beego/logs instead.
SetLogger sets a new logger.
SetStaticPath sets static directory path and proper url pattern in beego application.
SetTemplateFSFunc set default filesystem function.
SetViewsPath sets view directory path in beego application.
Str2html Convert string to template.HTML type.
Substr returns the substr from start to length.
TestBeegoInit is for test package init.
Trace logs a message at trace level.
UnregisterFixedRoute unregisters the route with the specified fixedRoute.
URLFor returns url string with another registered controller handler with params.
Walk walks the file tree rooted at root in filesystem, calling walkFn for each file or directory in the tree, including root.
Warn compatibility alias for Warning() Deprecated: use github.com/OpenStars/beego/logs instead.
Warning logs a message at warning level.
# Constants
default filter execution points.
default filter execution points.
default filter execution points.
default filter execution points.
DEV is for develop.
default filter execution points.
Log levels to control the logging output.
Log levels to control the logging output.
Log levels to control the logging output.
Log levels to control the logging output.
Log levels to control the logging output.
Log levels to control the logging output.
Log levels to control the logging output.
Log levels to control the logging output.
PROD is for production.
VERSION represent beego web framework version.
# Variables
AppConfig is the instance of Config, store the config information from file.
AppPath is the absolute path to the app.
BConfig is the default config for Application.
BeeApp is an application instance.
BeeLogger references the used application logger.
DefaultAccessLogFilter will skip the accesslog if return true.
ErrAbort custom error when user stop request handler manually.
ErrorMaps holds map of http handlers for each error string.
FilterMonitorFunc is default monitor filter when admin module is enable.
GlobalControllerRouter store comments with controller.
GlobalSessions is the instance for the session manager.
HTTPMETHOD list the supported http methods.
# Structs
App defines beego application with a new PatternServeMux.
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.
ControllerComments store the comment for the controller method.
ControllerFilter store the filter for controller.
ControllerFilterComments store the comment for controller level filter.
ControllerImportComments store the import comment for controller needed.
ControllerInfo holds information about the controller.
ControllerRegister containers registered router rules, controller handlers and filters.
No description provided by the author
FilterRouter defines a filter operation which is invoked before the controller handler is executed.
FlashData is a tools to maintain data when using across request.
Listen holds for http and https related config.
LogConfig holds Log related config.
Namespace is store all the info.
SessionConfig holds session related config.
Tree has three elements: FixRouter/wildcard/leaves fixRouter stores Fixed Router wildcard stores params leaves store the endpoint information.
WebConfig holds web related config.
# Interfaces
ControllerInterface is an interface to uniform all controller handler.
FilterHandler is an interface for.
# Type aliases
ControllerCommentsSlice implements the sort interface.
FilterFunc defines a filter function which is invoked before the controller handler is executed.
LinkNamespace used as link action.
M is Map shortcut.
MiddleWare function for http.Handler.
PolicyFunc defines a policy function which is invoked before the controller handler is executed.