cd480129 by Unknown

update

1 parent 140b513c
1 ## Beego 1 #Beego
2 ======== 2 Beego is a lightweight, open source, non-blocking and scalable web framework for the Go programming language. It's like tornado in Python. This web framework has already been using for building web server and tools in SNDA's CDN system. Documentation and downloads available at [http://astaxie.github.com/beego](http://astaxie.github.com/beego)
3 Beego is a lightweight, open source, non-blocking and scalable web framework for the Go programming language. It's like tornado in Python. This web framework has already been using for building web server and tools in SNDA's CDN system. It has following main features: 3
4 It has following main features:
4 5
5 - Supports MVC model, you only need to focus on logic and implementation methods. 6 - Supports MVC model, you only need to focus on logic and implementation methods.
6 - Supports websocket, use customized handlers to integrate sockjs. 7 - Supports websocket, use customized handlers to integrate sockjs.
...@@ -11,422 +12,41 @@ Beego is a lightweight, open source, non-blocking and scalable web framework for ...@@ -11,422 +12,41 @@ Beego is a lightweight, open source, non-blocking and scalable web framework for
11 - Use configuration file (.ini) to customized your system. 12 - Use configuration file (.ini) to customized your system.
12 - Use built-in templates in Go, and it provides much more useful functions which are commonly used in web development. 13 - Use built-in templates in Go, and it provides much more useful functions which are commonly used in web development.
13 14
14 The working principles of Beego as follows. 15 The working principles of Beego as follows:
16
15 ![](images/beego.png) 17 ![](images/beego.png)
16 18
17 Beego is licensed under the Apache Licence, Version 2.0 19 Beego is licensed under the Apache Licence, Version 2.0
18 (http://www.apache.org/licenses/LICENSE-2.0.html). 20 (http://www.apache.org/licenses/LICENSE-2.0.html).
19 21
20 ## Installation 22 #Simple example
21 ============ 23 The following example prints string "Hello world" to your browser, it shows how easy to build a web application with Beego.
22 To install:
23
24 go get github.com/astaxie/beego
25
26 ## Quick Start
27 ============
28 Here is the canonical "Hello, world" example app for beego:
29 ```go
30 package main
31
32 import (
33 "github.com/astaxie/beego"
34 )
35
36 type MainController struct {
37 beego.Controller
38 }
39
40 func (this *MainController) Get() {
41 this.Ctx.WriteString("hello world")
42 }
43
44 func main() {
45 beego.Router("/", &MainController{})
46 //beego.HttpPort = 8080 // default
47 beego.Run()
48 }
49 ```
50
51 http get http://localhost:8080/
52 HTTP/1.1 200 OK
53 Content-Type: text/plain; charset=utf-8
54 Date: Sat, 15 Dec 2012 16:03:00 GMT
55 Transfer-Encoding: chunked
56
57 hello world
58
59 A more complete example use of beego exists here:[beepkg](https://github.com/astaxie/beepkg)
60
61 Some associated tools for beego reside in:[bee](https://github.com/astaxie/bee)
62
63 ## Router
64 ============
65 In beego, a route is a struct paired with a URL-matching pattern. The struct has many method with the same name of http method to serve the http response. Each route is associated with a block.
66 ```go
67 beego.Router("/", &controllers.MainController{})
68 beego.Router("/admin", &admin.UserController{})
69 beego.Router("/admin/index", &admin.ArticleController{})
70 beego.Router("/admin/addpkg", &admin.AddController{})
71 ```
72 You can specify custom regular expressions for routes:
73 ```go
74 beego.Router("/admin/editpkg/:id([0-9]+)", &admin.EditController{})
75 beego.Router("/admin/delpkg/:id([0-9]+)", &admin.DelController{})
76 beego.Router("/:pkg(.*)", &controllers.MainController{})
77 ```
78 You can also create routes for static files:
79
80 beego.BeeApp.SetStaticPath("/static","/public")
81
82 This will serve any files in /static, including files in subdirectories. For example request `/static/logo.gif` or `/static/style/main.css` will server with the file in the path `/pulic/logo.gif` or `/public/style/main.css`
83
84 ## Filters / Middleware
85 ============
86 You can apply filters to routes, which is useful for enforcing security, redirects, etc.
87
88 You can, for example, filter all request to enforce some type of security:
89 ```go
90 var FilterUser = func(w http.ResponseWriter, r *http.Request) {
91 if r.URL.User == nil || r.URL.User.Username() != "admin" {
92 http.Error(w, "", http.StatusUnauthorized)
93 }
94 }
95
96 beego.Filter(FilterUser)
97 ```
98 You can also apply filters only when certain REST URL Parameters exist:
99 ```go
100 beego.Router("/:id([0-9]+)", &admin.EditController{})
101 beego.FilterParam("id", func(rw http.ResponseWriter, r *http.Request) {
102 ...
103 })
104 ```
105 Additionally, You can apply filters only when certain prefix URL path exist:
106 ```go
107 beego.FilterPrefixPath("/admin", func(rw http.ResponseWriter, r *http.Request) {
108 auth
109 })
110 ```
111
112 ## Controller / Struct
113 ============
114 To implement a beego Controller, embed the `beego.Controller` struct:
115 ```go
116 type xxxController struct {
117 beego.Controller
118 }
119 ```
120 `beego.Controller` satisfieds the `beego.ControllerInterface` interface, which defines the following methods:
121
122 - Init(ct *Context, cn string)
123
124 this function is init the Context, ChildStruct' name and the Controller's variables.
125
126 - Prepare()
127
128 this function is Run before the HTTP METHOD's Function,as follow defined. In the ChildStruct you can define this function to auth user or init database et.
129
130 - Get()
131
132 When the HTTP' Method is GET, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing.
133
134 - Post()
135
136 When the HTTP' Method is POST, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing.
137
138 - Delete()
139
140 When the HTTP' Method is DELETE, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing.
141
142 - Put()
143
144 When the HTTP' Method is PUT, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing.
145
146 - Head()
147 24
148 When the HTTP' Method is HEAD, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing. 25 package main
149 26
150 - Patch() 27 import (
28 "github.com/astaxie/beego"
29 )
151 30
152 When the HTTP' Method is PATCH, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing. 31 type MainController struct {
153 32 beego.Controller
154 - Options()
155
156 When the HTTP' Method is OPTIONS, the beego router will run this function.Default is HTTP-403. In the ChildStruct you must define the same functon to logical processing.
157
158 - Finish()
159
160 this function is run after the HTTP METHOD's Function,as previous defined. In the ChildStruct you can define this function to close database et.
161
162 - Render() error
163
164 this function is to render the template as user defined. In the strcut you need to call.
165
166
167 So you can define ChildStruct method to accomplish the interface's method, now let us see an example:
168 ```go
169 type AddController struct {
170 beego.Controller
171 }
172
173 func (this *AddController) Prepare() {
174
175 }
176
177 func (this *AddController) Get() {
178 this.Layout = "admin/layout.html"
179 this.TplNames = "admin/add.tpl"
180 }
181
182 func (this *AddController) Post() {
183 //data deal with
184 this.Ctx.Request.ParseForm()
185 pkgname := this.Ctx.Request.Form.Get("pkgname")
186 content := this.Ctx.Request.Form.Get("content")
187 beego.Info(this.Ctx.Request.Form)
188 pk := models.GetCruPkg(pkgname)
189 if pk.Id == 0 {
190 var pp models.PkgEntity
191 pp.Pid = 0
192 pp.Pathname = pkgname
193 pp.Intro = pkgname
194 models.InsertPkg(pp)
195 pk = models.GetCruPkg(pkgname)
196 } 33 }
197 var at models.Article
198 at.Pkgid = pk.Id
199 at.Content = content
200 models.InsertArticle(at)
201 this.Ctx.Redirect(302, "/admin/index")
202 }
203 ```
204 ## View / Template
205 ============
206 ### template view path
207
208 The default viewPath is `/views`, you can put the template file in the views. beego will find the template from viewpath.
209
210 also you can modify the viewpaths like this:
211
212 beego.ViewsPath = "/myviewpath"
213
214 ### template names
215 beego will find the template from viewpath. the file is set by user like:
216
217 this.TplNames = "admin/add.tpl"
218
219 then beego will find the file in the path:`/views/admin/add.tpl`
220
221 if you don't set TplNames,beego will find like this:
222
223 c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt
224
225 So if the ChildName="AddController",Request Method= "POST",default TplEXT="tpl"
226 So beego will file the file in the path:`/view/AddController/POST.tpl`
227
228 ### autoRender
229 In the controller you needn't to call render function. beego will auto call this function after HTTP Method Call.
230
231 You can disable automatic invokation of autorender via the AutoRender Flag:
232 ```go
233 beego.AutoRender = false
234 ```
235
236 ### layout
237 beego supports layouts for views. For example:
238 ```go
239 this.Layout = "admin/layout.html"
240 this.TplNames = "admin/add.tpl"
241 ```
242
243 In layout.html you must define the variable like this to show sub template's content:
244
245 {{.LayoutContent}}
246
247 beego first parses the TplNames files, renders their content, and appends it to data["LayoutContent"].
248 34
249 ### template function 35 func (this *MainController) Get() {
250 beego support users to define template function like this: 36 this.Ctx.WriteString("hello world")
251 ```go
252 func hello(in string)(out string){
253 out = in + "world"
254 return
255 }
256
257 beego.AddFuncMap("hi",hello)
258 ```
259
260 then in you template you can use it like this:
261
262 {{.Content | hi}}
263
264 beego has three default defined funtion:
265
266 - beegoTplFuncMap["markdown"] = MarkDown
267
268 MarkDown parses a string in MarkDown format and returns HTML. Used by the template parser as "markdown"
269
270 - beegoTplFuncMap["dateformat"] = DateFormat
271
272 DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"
273
274 - beegoTplFuncMap["compare"] = Compare
275
276 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"
277
278 ### JSON/XML output
279 You can use `beego.Controller.ServeJson` or `beego.Controller.ServeXml` for serializing to Json and Xml. I found myself constantly writing code to serialize, set content type, content length, etc. Feel free to use these functions to eliminate redundant code in your app.
280
281 Helper function for serving Json, sets content type to application/json:
282 ```go
283 func (this *AddController) Get() {
284 mystruct := { ... }
285 this.Data["json"] = &mystruct
286 this.ServeJson()
287 }
288 ```
289 Helper function for serving Xml, sets content type to application/xml:
290 ```go
291 func (this *AddController) Get() {
292 mystruct := { ... }
293 this.Data["xml"]=&mystruct
294 this.ServeXml()
295 }
296 ```
297
298 ## Beego Variables
299 ============
300 beego has many default variables, as follow is a list to show:
301
302 - BeeApp *App
303
304 global app init by the beego. You needn't to init it, just use it.
305
306 - AppName string
307
308 appname is what you project named, default is beego
309
310 - AppPath string
311
312 this is the project path
313
314 - StaticDir map[string]string
315
316 staticdir store the map which request url to the static file path
317
318 default is the request url has prefix `static`, then server the path in the app path
319
320 - HttpAddr string
321
322 http listen address, defult is ""
323
324 - HttpPort int
325
326 http listen port, default is 8080
327
328 - RecoverPanic bool
329
330 RecoverPanic mean when the program panic whether the process auto recover,default is true
331
332 - AutoRender bool
333
334 whether run the Render function, default is true
335
336 - ViewsPath string
337
338 the template path, default is /views
339
340 - RunMode string //"dev" or "prod"
341
342 the runmode ,default is prod
343
344 - AppConfig *Config
345
346 Appconfig is a result that parse file from conf/app.conf, if this file not exist then the variable is nil. if the file exist, then return the Config as follow.
347
348 - PprofOn bool
349
350 default is false. turn on pprof, if set to true. you can visit like this:
351
352 /debug/pprof
353 /debug/pprof/cmdline
354 /debug/pprof/profile
355 /debug/pprof/symbol
356 this serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool. For more information about pprof, see http://golang.org/pkg/net/http/pprof/
357
358 ## Config
359 ============
360
361 beego support parse ini file, beego will parse the default file in the path `conf/app.conf`
362
363 throw this conf file you can set many Beego Variables to change default values.
364
365 app.conf
366
367 appname = beepkg
368 httpaddr = "127.0.0.1"
369 httpport = 9090
370 runmode ="dev"
371 autorender = false
372 autorecover = false
373 viewspath = "myview"
374
375 this variables will replace the default beego variable's values
376
377 you can also set you own variables such as database setting
378
379 mysqluser = "root"
380 mysqlpass = "rootpass"
381 mysqlurls = "127.0.0.1"
382 mysqldb = "beego"
383
384 In you app you can get the config like this:
385
386 beego.AppConfig.String("mysqluser")
387 beego.AppConfig.String("mysqlpass")
388 beego.AppConfig.String("mysqlurls")
389 beego.AppConfig.String("mysqldb")
390
391 ## Logger
392 ============
393 beego has a default log named BeeLogger which output to os.Stdout.
394
395 you can change it output with the standard log.Logger like this:
396
397 fd,err := os.OpenFile("/opt/app/beepkg/beepkg.log", os.O_RDWR|os.O_APPEND, 0644)
398 if err != nil {
399 beego.Critical("openfile beepkg.log:", err)
400 return
401 } 37 }
402 lg := log.New(fd, "", log.Ldate|log.Ltime)
403 beego.SetLogger(lg)
404
405 38
406 ### Supported log levels 39 func main() {
407 - Trace - For pervasive information on states of all elementary constructs. Use 'Trace' for in-depth debugging to find problem parts of a function, to check values of temporary variables, etc. 40 beego.Router("/", &MainController{})
408 - Debug - For detailed system behavior reports and diagnostic messages to help to locate problems during development. 41 beego.Run()
409 - Info - For general information on the application's work. Use 'Info' level in your code so that you could leave it 'enabled' even in production. So it is a 'production log level'. 42 }
410 - Warn - For indicating small errors, strange situations, failures that are automatically handled in a safe manner.
411 - Error - For severe failures that affects application's workflow, not fatal, however (without forcing app shutdown).
412 - Critical - For producing final messages before application’s death. Note: critical messages force immediate flush because in critical situation it is important to avoid log message losses if app crashes.
413 - Off - A special log level used to turn off logging
414
415 beego has follow functions:
416
417 - Trace(v ...interface{})
418 - Debug(v ...interface{})
419 - Info(v ...interface{})
420 - Warn(v ...interface{})
421 - Error(v ...interface{})
422 - Critical(v ...interface{})
423
424 you can set log levels like this :
425
426 beego.SetLevel(beego.LevelError)
427
428 after set the log levels, in the logs function which below the setlevels willn't output anything
429 43
430 after set levels to beego.LevelError 44 #Handbook
45 - [Purposes of design Beego](Why.md)
46 - [Installation](Install.md)
47 - [Quick start](Quickstart.md)
48 - [Step by step](Tutorial.md)
49 - [Real world usage](Application.md)
431 50
432 Trace, Debug, Info, Warn will not output anything. So you can change it when in dev and prod mode.
...\ No newline at end of file ...\ No newline at end of file
51 #Documentation
52 [godoc](http://godoc.org/github.com/astaxie/beego)
...\ No newline at end of file ...\ No newline at end of file
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!