541d7f71 by Dobrosław Żybort

Update: clean and fix docs markdown

1 parent fdb94aeb
1 ##What is hot update? 1 ## What is hot update?
2
2 If you have used nginx, you may know that nginx supports hot update, which means you can update your nginx without stopping and restarting it. It serves old connections with old version, and accepts new connections with new version. Notice that hot compiling is different from hot update, where hot compiling is monitoring your source files and recompile them when the content changes, it requires stop and restart your applications, `bee start` is a tool for hot compiling. 3 If you have used nginx, you may know that nginx supports hot update, which means you can update your nginx without stopping and restarting it. It serves old connections with old version, and accepts new connections with new version. Notice that hot compiling is different from hot update, where hot compiling is monitoring your source files and recompile them when the content changes, it requires stop and restart your applications, `bee start` is a tool for hot compiling.
3 4
4 ##Is hot update necessary? 5
6 ## Is hot update necessary?
7
5 Some people says that hot update is not as useful as its cool name. In my opinion, this is absolutely necessary because zero-down server is our goal for our services. Even though sometimes some errors or hardware problems may occur, but it belongs to design of high availability, don't mix them up. Service update is a known issue, so we need to fix this problem. 8 Some people says that hot update is not as useful as its cool name. In my opinion, this is absolutely necessary because zero-down server is our goal for our services. Even though sometimes some errors or hardware problems may occur, but it belongs to design of high availability, don't mix them up. Service update is a known issue, so we need to fix this problem.
6 9
7 ##How Beego support hot update? 10
11 ## How Beego support hot update?
12
8 The basic principle of hot update: main process fork a process, and child process execute corresponding programs. So what happens? We know that after forked a process, main process will have all handles, data and stack, etc, but all handles are saved in `CloseOnExec`, so all copied handles will be closed when you execute it unless you clarify this, and we need child process to reuse the handle of `net.Listener`. Once a process calls exec functions, it is "dead", system replaces it with new code. The only thing it left is the process ID, which is the same number but it is a new program after executed. 13 The basic principle of hot update: main process fork a process, and child process execute corresponding programs. So what happens? We know that after forked a process, main process will have all handles, data and stack, etc, but all handles are saved in `CloseOnExec`, so all copied handles will be closed when you execute it unless you clarify this, and we need child process to reuse the handle of `net.Listener`. Once a process calls exec functions, it is "dead", system replaces it with new code. The only thing it left is the process ID, which is the same number but it is a new program after executed.
9 14
10 Therefore, the first thing we need to do is that let child process fork main process and through `os.StartProcess` to append files that contains handle that is going to be inherited. 15 Therefore, the first thing we need to do is that let child process fork main process and through `os.StartProcess` to append files that contains handle that is going to be inherited.
...@@ -15,7 +20,8 @@ The final step is that we want to serve old connections with old version of appl ...@@ -15,7 +20,8 @@ The final step is that we want to serve old connections with old version of appl
15 20
16 Above are three problems that we need to solve, you can see my code logic for specific implementation. 21 Above are three problems that we need to solve, you can see my code logic for specific implementation.
17 22
18 ##Show time 23
24 ## Show time
19 25
20 1. Write code in your Get method: 26 1. Write code in your Get method:
21 27
...@@ -29,7 +35,7 @@ Above are three problems that we need to solve, you can see my code logic for sp ...@@ -29,7 +35,7 @@ Above are three problems that we need to solve, you can see my code logic for sp
29 35
30 One execute: ` ps -ef|grep <application name>` 36 One execute: ` ps -ef|grep <application name>`
31 37
32 Another one execute:`curl "http://127.0.0.1:8080/?sleep=20"` 38 Another one execute: `curl "http://127.0.0.1:8080/?sleep=20"`
33 39
34 3. Hot update 40 3. Hot update
35 41
......
1 #Installation 1 # Installation
2
2 Beego is a simple web framework, but it uses many third-party packages, so you have to install all dependency packages also. 3 Beego is a simple web framework, but it uses many third-party packages, so you have to install all dependency packages also.
3 4
4 - Before anything you do, you have to check that you installed Go in your computer, see more detail about Go installation in my book: [Chapter 1](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/01.1.md) 5 - Before anything you do, you have to check that you installed Go in your computer, see more detail about Go installation in my book: [Chapter 1](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/01.1.md)
......
1 # Quick start 1 # Quick start
2
2 Hey, you say you've never heard about Beego and don't know how to use it? Don't worry, after you read this section, you will know a lot about Beego. Before you start reading, make sure you installed Beego in your computer, if not, check this tutorial: [Installation](Install.md) 3 Hey, you say you've never heard about Beego and don't know how to use it? Don't worry, after you read this section, you will know a lot about Beego. Before you start reading, make sure you installed Beego in your computer, if not, check this tutorial: [Installation](Install.md)
3 4
4 **Navigation** 5 **Navigation**
...@@ -23,7 +24,9 @@ Hey, you say you've never heard about Beego and don't know how to use it? Don't ...@@ -23,7 +24,9 @@ Hey, you say you've never heard about Beego and don't know how to use it? Don't
23 - [Integrated third-party applications](#integrated-third-party-applications) 24 - [Integrated third-party applications](#integrated-third-party-applications)
24 - [Deployment](#deployment) 25 - [Deployment](#deployment)
25 26
27
26 ## Hello world 28 ## Hello world
29
27 This is an example of "Hello world" in Beego: 30 This is an example of "Hello world" in Beego:
28 31
29 package main 32 package main
...@@ -54,14 +57,21 @@ Open address [http://127.0.0.1:8080](http://127.0.0.1:8080) in your browser and ...@@ -54,14 +57,21 @@ Open address [http://127.0.0.1:8080](http://127.0.0.1:8080) in your browser and
54 57
55 What happened in behind above example? 58 What happened in behind above example?
56 59
57 1. We import package `github.com/astaxie/beego`. As we know that Go initialize packages and runs init() function in every package(more detail [here](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/02.3.md#main-function-and-init-function)), so Beego initializes the BeeApp application at this time. 60 1. We import package `github.com/astaxie/beego`. As we know that Go initialize packages and runs init() function in every package ([more details](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/02.3.md#main-function-and-init-function)), so Beego initializes the BeeApp application at this time.
61
58 2. Define controller. We define a struct called `MainController` with a anonymous field `beego.Controller`, so the `MainController` has all methods that `beego.Controller` has. 62 2. Define controller. We define a struct called `MainController` with a anonymous field `beego.Controller`, so the `MainController` has all methods that `beego.Controller` has.
63
59 3. Define RESTful methods. Once we use anonymous combination, `MainController` has already had `Get`, `Post`, `Delete`, `Put` and other methods, these methods will be called when user sends corresponding request, like `Post` method for requests that are using POST method. Therefore, after we overloaded `Get` method in `MainController`, all GET requests will use `Get` method in `MainController` instead of in `beego.Controller`. 64 3. Define RESTful methods. Once we use anonymous combination, `MainController` has already had `Get`, `Post`, `Delete`, `Put` and other methods, these methods will be called when user sends corresponding request, like `Post` method for requests that are using POST method. Therefore, after we overloaded `Get` method in `MainController`, all GET requests will use `Get` method in `MainController` instead of in `beego.Controller`.
65
60 4. Define main function. All applications in Go use main function as entry point as C does. 66 4. Define main function. All applications in Go use main function as entry point as C does.
67
61 5. Register routers, it tells Beego which controller is responsibility for specific requests. Here we register `/` for `MainController`, so all requests in `/` will be handed to `MainController`. Be aware that the first argument is the path and the second one is pointer of controller that you want to register. 68 5. Register routers, it tells Beego which controller is responsibility for specific requests. Here we register `/` for `MainController`, so all requests in `/` will be handed to `MainController`. Be aware that the first argument is the path and the second one is pointer of controller that you want to register.
69
62 6. Run application in port 8080 as default, press `Ctrl+c` to exit. 70 6. Run application in port 8080 as default, press `Ctrl+c` to exit.
63 71
72
64 ## New project 73 ## New project
74
65 Get into your $GOPATH, then use following command to setup Beego project: 75 Get into your $GOPATH, then use following command to setup Beego project:
66 76
67 bee create hello 77 bee create hello
...@@ -82,7 +92,9 @@ It generates folders and files for your project, directory structure as follows: ...@@ -82,7 +92,9 @@ It generates folders and files for your project, directory structure as follows:
82 └── views 92 └── views
83 └── index.tpl 93 └── index.tpl
84 94
95
85 ## Development mode 96 ## Development mode
97
86 Beego uses development mode as default, you can use following code to change mode in your application: 98 Beego uses development mode as default, you can use following code to change mode in your application:
87 99
88 beego.RunMode = "pro" 100 beego.RunMode = "pro"
...@@ -104,7 +116,9 @@ In development mode, you have following effects: ...@@ -104,7 +116,9 @@ In development mode, you have following effects:
104 116
105 ![](images/dev.png) 117 ![](images/dev.png)
106 118
119
107 ## Router 120 ## Router
121
108 The main function of router is to connect request URL and handler. Beego wrapped `Controller`, so it connects request URL and `ControllerInterface`. The `ControllerInterface` has following methods: 122 The main function of router is to connect request URL and handler. Beego wrapped `Controller`, so it connects request URL and `ControllerInterface`. The `ControllerInterface` has following methods:
109 123
110 type ControllerInterface interface { 124 type ControllerInterface interface {
...@@ -160,7 +174,9 @@ For more convenient configure route rules, Beego references the idea from sinatr ...@@ -160,7 +174,9 @@ For more convenient configure route rules, Beego references the idea from sinatr
160 174
161 Match type string // match :hi is string type, Beego uses regular expression ([\w]+) automatically 175 Match type string // match :hi is string type, Beego uses regular expression ([\w]+) automatically
162 176
163 ##Static files 177
178 ## Static files
179
164 Go provides `http.ServeFile` for static files, Beego wrapped this function and use following way to register static file folder: 180 Go provides `http.ServeFile` for static files, Beego wrapped this function and use following way to register static file folder:
165 181
166 beego.SetStaticPath("/static","public") 182 beego.SetStaticPath("/static","public")
...@@ -176,7 +192,9 @@ Beego supports multiple static file directories as follows: ...@@ -176,7 +192,9 @@ Beego supports multiple static file directories as follows:
176 192
177 After you setting static directory, when users visit `/images/login/login.png`,Beego accesses `images/login/login.png` in related to your application directory. One more example, if users visit `/static/img/logo.png`, Beego accesses file `public/img/logo.png`. 193 After you setting static directory, when users visit `/images/login/login.png`,Beego accesses `images/login/login.png` in related to your application directory. One more example, if users visit `/static/img/logo.png`, Beego accesses file `public/img/logo.png`.
178 194
179 ##Filter and middleware 195
196 ## Filter and middleware
197
180 Beego supports customized filter and middleware, such as security verification, force redirect, etc. 198 Beego supports customized filter and middleware, such as security verification, force redirect, etc.
181 199
182 Here is an example of verify user name of all requests, check if it's admin. 200 Here is an example of verify user name of all requests, check if it's admin.
...@@ -202,7 +220,9 @@ Filter by prefix is also available: ...@@ -202,7 +220,9 @@ Filter by prefix is also available:
202 dosomething() 220 dosomething()
203 }) 221 })
204 222
205 ##Controller 223
224 ## Controller
225
206 Use `beego.controller` as anonymous in your controller struct to implement the interface in Beego: 226 Use `beego.controller` as anonymous in your controller struct to implement the interface in Beego:
207 227
208 type xxxController struct { 228 type xxxController struct {
...@@ -266,7 +286,7 @@ Overload all methods for all customized logic processes, let's see an example: ...@@ -266,7 +286,7 @@ Overload all methods for all customized logic processes, let's see an example:
266 } 286 }
267 287
268 func (this *AddController) Get() { 288 func (this *AddController) Get() {
269 this.Data["content"] ="value" 289 this.Data["content"] = "value"
270 this.Layout = "admin/layout.html" 290 this.Layout = "admin/layout.html"
271 this.TplNames = "admin/add.tpl" 291 this.TplNames = "admin/add.tpl"
272 } 292 }
...@@ -290,13 +310,19 @@ Overload all methods for all customized logic processes, let's see an example: ...@@ -290,13 +310,19 @@ Overload all methods for all customized logic processes, let's see an example:
290 this.Ctx.Redirect(302, "/admin/index") 310 this.Ctx.Redirect(302, "/admin/index")
291 } 311 }
292 312
293 ##Template 313
294 ###Template directory 314 ## Template
315
316
317 ### Template directory
318
295 Beego uses `views` as the default directory for template files, parses and caches them as needed(cache is not enable in develop mode), but you can **change**(because only one directory can be used for template files) its directory using following code: 319 Beego uses `views` as the default directory for template files, parses and caches them as needed(cache is not enable in develop mode), but you can **change**(because only one directory can be used for template files) its directory using following code:
296 320
297 beego.ViewsPath = "/myviewpath" 321 beego.ViewsPath = "/myviewpath"
298 322
299 ###Auto-render 323
324 ### Auto-render
325
300 You don't need to call render function manually, Beego calls it automatically after corresponding methods executed. If your application is somehow doesn't need templates, you can disable this feature either in code of `main.go` or configuration file. 326 You don't need to call render function manually, Beego calls it automatically after corresponding methods executed. If your application is somehow doesn't need templates, you can disable this feature either in code of `main.go` or configuration file.
301 327
302 To disable auto-render in configuration file: 328 To disable auto-render in configuration file:
...@@ -307,13 +333,17 @@ To disable auto-render in `main.go`(before you call `beego.Run()` to run the app ...@@ -307,13 +333,17 @@ To disable auto-render in `main.go`(before you call `beego.Run()` to run the app
307 333
308 beego.AutoRender = false 334 beego.AutoRender = false
309 335
310 ###Template data 336
337 ### Template data
338
311 You can use `this.Data` in controller methods to access the data in templates. Suppose you want to get content of `{{.Content}}`, you can use following code to do this: 339 You can use `this.Data` in controller methods to access the data in templates. Suppose you want to get content of `{{.Content}}`, you can use following code to do this:
312 340
313 this.Data["Context"] = "value" 341 this.Data["Context"] = "value"
314 342
315 ###Template name 343
316 Beego uses built-in template engine of Go, so there is no different in syntax. As for how to write template file, please visit [Template tutorial](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/07.4.md) 344 ### Template name
345
346 Beego uses built-in template engine of Go, so there is no different in syntax. As for how to write template file, please visit [Template tutorial](https://github.com/Unknwon/build-web-application-with-golang_EN/blob/master/eBook/07.4.md).
317 347
318 Beego parses template files in `viewpath` and render it after you set the name of the template file in controller methods. For example, Beego finds the file `add.tpl` in directory `admin` in following code: 348 Beego parses template files in `viewpath` and render it after you set the name of the template file in controller methods. For example, Beego finds the file `add.tpl` in directory `admin` in following code:
319 349
...@@ -329,7 +359,9 @@ If you enabled auto-render and you don't tell Beego which template file you are ...@@ -329,7 +359,9 @@ If you enabled auto-render and you don't tell Beego which template file you are
329 359
330 Which is `<corresponding controller name>/<request method name>.<template extension>`. For example, your controller name is `AddController` and the request method is POST, and the default file extension is `tpl`, so Beego will try to find file `/<viewpath>/AddController/POST.tpl`. 360 Which is `<corresponding controller name>/<request method name>.<template extension>`. For example, your controller name is `AddController` and the request method is POST, and the default file extension is `tpl`, so Beego will try to find file `/<viewpath>/AddController/POST.tpl`.
331 361
332 ###Layout design 362
363 ### Layout design
364
333 Beego supports layout design, which means if you are working on an administration application, and some part of its user interface is exactly same all the time, then you can make this part as a layout. 365 Beego supports layout design, which means if you are working on an administration application, and some part of its user interface is exactly same all the time, then you can make this part as a layout.
334 366
335 this.Layout = "admin/layout.html" 367 this.Layout = "admin/layout.html"
...@@ -347,7 +379,9 @@ Right now, Beego caches all template files, so you can use following way to impl ...@@ -347,7 +379,9 @@ Right now, Beego caches all template files, so you can use following way to impl
347 Handle logic 379 Handle logic
348 {{template "footer.html"}} 380 {{template "footer.html"}}
349 381
350 ###Template function 382
383 ### Template function
384
351 Beego supports customized template functions that are registered before you call `beego.Run()`. 385 Beego supports customized template functions that are registered before you call `beego.Run()`.
352 386
353 func hello(in string)(out string){ 387 func hello(in string)(out string){
...@@ -366,32 +400,42 @@ There are some built-in template functions: ...@@ -366,32 +400,42 @@ There are some built-in template functions:
366 * markdown 400 * markdown
367 401
368 This function converts markdown content to HTML format, use {{markdown .Content}} in template files. 402 This function converts markdown content to HTML format, use {{markdown .Content}} in template files.
403
369 * dateformat 404 * dateformat
370 405
371 This function converts time to formatted string, use {{dateformat .Time "2006-01-02T15:04:05Z07:00"}} in template files. 406 This function converts time to formatted string, use {{dateformat .Time "2006-01-02T15:04:05Z07:00"}} in template files.
407
372 * date 408 * date
373 409
374 This function implements date function like in PHP, use formatted string to get corresponding time, use {{date .T "Y-m-d H:i:s"}} in template files. 410 This function implements date function like in PHP, use formatted string to get corresponding time, use {{date .T "Y-m-d H:i:s"}} in template files.
411
375 * compare 412 * compare
376 413
377 This functions compares two objects, returns true if they are same, false otherwise, use {{compare .A .B}} in template files. 414 This functions compares two objects, returns true if they are same, false otherwise, use {{compare .A .B}} in template files.
415
378 * substr 416 * substr
379 417
380 This function cuts out string from another string by index, it supports UTF-8 characters, use {{substr .Str 0 30}} in template files. 418 This function cuts out string from another string by index, it supports UTF-8 characters, use {{substr .Str 0 30}} in template files.
419
381 * html2str 420 * html2str
382 421
383 This function escapes HTML to raw string, use {{html2str .Htmlinfo}} in template files. 422 This function escapes HTML to raw string, use {{html2str .Htmlinfo}} in template files.
423
384 * str2html 424 * str2html
385 425
386 This function outputs string in HTML format without escaping, use {{str2html .Strhtml}} in template files. 426 This function outputs string in HTML format without escaping, use {{str2html .Strhtml}} in template files.
427
387 * htmlquote 428 * htmlquote
388 429
389 This functions implements basic HTML escape, use {{htmlquote .quote}} in template files. 430 This functions implements basic HTML escape, use {{htmlquote .quote}} in template files.
431
390 * htmlunquote 432 * htmlunquote
391 433
392 This functions implements basic invert-escape of HTML, use {{htmlunquote .unquote}} in template files. 434 This functions implements basic invert-escape of HTML, use {{htmlunquote .unquote}} in template files.
393 435
394 ##Handle request 436
437 ## Handle request
438
395 We always need to get data from users, including methods like GET, POST, etc. Beego parses these data automatically, and you can access them by following code: 439 We always need to get data from users, including methods like GET, POST, etc. Beego parses these data automatically, and you can access them by following code:
396 440
397 - GetString(key string) string 441 - GetString(key string) string
...@@ -417,10 +461,12 @@ If you need other types that are not included above, like you need int64 instead ...@@ -417,10 +461,12 @@ If you need other types that are not included above, like you need int64 instead
417 461
418 To use `this.Ctx.Request` for more information about request, and object properties and method please read [Request](http://golang.org/pkg/net/http/#Request) 462 To use `this.Ctx.Request` for more information about request, and object properties and method please read [Request](http://golang.org/pkg/net/http/#Request)
419 463
420 ###File upload 464
465 ### File upload
466
421 It's very easy to upload file through Beego, but don't forget to add `enctype="multipart/form-data"` in your form, otherwise the browser will not upload anything. 467 It's very easy to upload file through Beego, but don't forget to add `enctype="multipart/form-data"` in your form, otherwise the browser will not upload anything.
422 468
423 Files will be saved in memory, if the size is greater than cache memory, the rest part will be saved as temporary file. The default cache memory is 64 MB, and you can using following ways to change this size. 469 Files will be saved in memory, if the size is greater than cache memory, the rest part will be saved as temporary file. The default cache memory is 64 MB, and you can use following ways to change this size.
424 470
425 In code: 471 In code:
426 472
...@@ -446,7 +492,9 @@ This is an example to save file that is uploaded: ...@@ -446,7 +492,9 @@ This is an example to save file that is uploaded:
446 this.SaveToFile("the_file","/var/www/uploads/uploaded_file.txt"") 492 this.SaveToFile("the_file","/var/www/uploads/uploaded_file.txt"")
447 } 493 }
448 494
449 ###Output Json and XML 495
496 ### Output Json and XML
497
450 Beego considered API function design at the beginning, and we often use Json or XML format data as output. Therefore, it's no reason that Beego doesn't support it: 498 Beego considered API function design at the beginning, and we often use Json or XML format data as output. Therefore, it's no reason that Beego doesn't support it:
451 499
452 Set `content-type` to `application/json` for output raw Json format data: 500 Set `content-type` to `application/json` for output raw Json format data:
...@@ -465,7 +513,9 @@ Set `content-type` to `application/xml` for output raw XML format data: ...@@ -465,7 +513,9 @@ Set `content-type` to `application/xml` for output raw XML format data:
465 this.ServeXml() 513 this.ServeXml()
466 } 514 }
467 515
468 ##Redirect and error 516
517 ## Redirect and error
518
469 You can use following to redirect: 519 You can use following to redirect:
470 520
471 func (this *AddController) Get() { 521 func (this *AddController) Get() {
...@@ -493,15 +543,15 @@ Then Beego will not execute rest code of the function body when you call `this.A ...@@ -493,15 +543,15 @@ Then Beego will not execute rest code of the function body when you call `this.A
493 543
494 Beego supports following error code: 404, 401, 403, 500 and 503, you can customize your error handle, for example, use following code to replace 404 error handle process: 544 Beego supports following error code: 404, 401, 403, 500 and 503, you can customize your error handle, for example, use following code to replace 404 error handle process:
495 545
496 func page_not_found(rw http.ResponseWriter, r *http.Request){ 546 func page_not_found(rw http.ResponseWriter, r *http.Request) {
497 t,_:= template.New("beegoerrortemp").ParseFiles(beego.ViewsPath+"/404.html") 547 t, _ := template.New("beegoerrortemp").ParseFiles(beego.ViewsPath + "/404.html")
498 data :=make(map[string]interface{}) 548 data := make(map[string]interface{})
499 data["content"] = "page not found" 549 data["content"] = "page not found"
500 t.Execute(rw, data) 550 t.Execute(rw, data)
501 } 551 }
502 552
503 func main() { 553 func main() {
504 beego.Errorhandler("404",page_not_found) 554 beego.Errorhandler("404", page_not_found)
505 beego.Router("/", &controllers.MainController{}) 555 beego.Router("/", &controllers.MainController{})
506 beego.Run() 556 beego.Run()
507 } 557 }
...@@ -510,22 +560,24 @@ You may be able to use your own `404.html` for your 404 error. ...@@ -510,22 +560,24 @@ You may be able to use your own `404.html` for your 404 error.
510 560
511 Beego also gives you ability to modify error message that shows on the error page, the following example shows how to set more meaningful error message when database has problems: 561 Beego also gives you ability to modify error message that shows on the error page, the following example shows how to set more meaningful error message when database has problems:
512 562
513 func dbError(rw http.ResponseWriter, r *http.Request){ 563 func dbError(rw http.ResponseWriter, r *http.Request) {
514 t,_:= template.New("beegoerrortemp").ParseFiles(beego.ViewsPath+"/dberror.html") 564 t, _ := template.New("beegoerrortemp").ParseFiles(beego.ViewsPath + "/dberror.html")
515 data :=make(map[string]interface{}) 565 data := make(map[string]interface{})
516 data["content"] = "database is now down" 566 data["content"] = "database is now down"
517 t.Execute(rw, data) 567 t.Execute(rw, data)
518 } 568 }
519 569
520 func main() { 570 func main() {
521 beego.Errorhandler("dbError",dbError) 571 beego.Errorhandler("dbError", dbError)
522 beego.Router("/", &controllers.MainController{}) 572 beego.Router("/", &controllers.MainController{})
523 beego.Run() 573 beego.Run()
524 } 574 }
525 575
526 After you registered this customized error, you can use `this.Abort("dbError")` for any database error in your applications. 576 After you registered this customized error, you can use `this.Abort("dbError")` for any database error in your applications.
527 577
528 ##Handle response 578
579 ## Handle response
580
529 There are some situations that you may have in response: 581 There are some situations that you may have in response:
530 582
531 1. Output template 583 1. Output template
...@@ -542,7 +594,9 @@ There are some situations that you may have in response: ...@@ -542,7 +594,9 @@ There are some situations that you may have in response:
542 594
543 this.Ctx.WriteString("ok") 595 this.Ctx.WriteString("ok")
544 596
597
545 ## Sessions 598 ## Sessions
599
546 Beego has a built-in session module and supports four engines, including memory, file, MySQL and redis. You can implement your own engine based on the interface. 600 Beego has a built-in session module and supports four engines, including memory, file, MySQL and redis. You can implement your own engine based on the interface.
547 601
548 It's easy to use session in Beego, use following code in your main() function: 602 It's easy to use session in Beego, use following code in your main() function:
...@@ -626,7 +680,9 @@ When the SessionProvider is redis, SessionSavePath is link address of redis, it ...@@ -626,7 +680,9 @@ When the SessionProvider is redis, SessionSavePath is link address of redis, it
626 beego.SessionProvider = "redis" 680 beego.SessionProvider = "redis"
627 beego.SessionSavePath = "127.0.0.1:6379" 681 beego.SessionSavePath = "127.0.0.1:6379"
628 682
683
629 ## Cache 684 ## Cache
685
630 Beego has a built-in cache module, it's like memcache, which caches data in memory. Here is an example of using cache module in Beego: 686 Beego has a built-in cache module, it's like memcache, which caches data in memory. Here is an example of using cache module in Beego:
631 687
632 var ( 688 var (
...@@ -670,7 +726,9 @@ To use cache, you need to initialize a `beego.NewBeeCache` object and set expire ...@@ -670,7 +726,9 @@ To use cache, you need to initialize a `beego.NewBeeCache` object and set expire
670 - Delete(name string) (ok bool, err error) 726 - Delete(name string) (ok bool, err error)
671 - IsExist(name string) bool 727 - IsExist(name string) bool
672 728
673 ##Safe map 729
730 ## Safe map
731
674 We know that map is not thread safe in Go, if you don't know it, this article may be helpful for you: [atomic_maps](http://golang.org/doc/faq#atomic_maps). However, we need a kind of thread safe map in practice, especially when we are using goroutines. Therefore, Beego provides a simple built-in thread safe map implementation. 732 We know that map is not thread safe in Go, if you don't know it, this article may be helpful for you: [atomic_maps](http://golang.org/doc/faq#atomic_maps). However, we need a kind of thread safe map in practice, especially when we are using goroutines. Therefore, Beego provides a simple built-in thread safe map implementation.
675 733
676 bm := NewBeeMap() 734 bm := NewBeeMap()
...@@ -697,7 +755,9 @@ This map has following interfaces: ...@@ -697,7 +755,9 @@ This map has following interfaces:
697 - Check(k interface{}) bool 755 - Check(k interface{}) bool
698 - Delete(k interface{}) 756 - Delete(k interface{})
699 757
700 ##Log 758
759 ## Log
760
701 Beego has a default BeeLogger object that outputs log into stdout, and you can use your own logger as well: 761 Beego has a default BeeLogger object that outputs log into stdout, and you can use your own logger as well:
702 762
703 beego.SetLogger(*log.Logger) 763 beego.SetLogger(*log.Logger)
...@@ -712,7 +772,8 @@ You can output everything that implemented `*log.Logger`, for example, write to ...@@ -712,7 +772,8 @@ You can output everything that implemented `*log.Logger`, for example, write to
712 lg := log.New(fd, "", log.Ldate|log.Ltime) 772 lg := log.New(fd, "", log.Ldate|log.Ltime)
713 beego.SetLogger(lg) 773 beego.SetLogger(lg)
714 774
715 ###Different levels of log 775
776 ### Different levels of log
716 777
717 * Trace(v ...interface{}) 778 * Trace(v ...interface{})
718 * Debug(v ...interface{}) 779 * Debug(v ...interface{})
...@@ -731,36 +792,48 @@ Your project may have a lot of log outputs, but you don't want to output everyth ...@@ -731,36 +792,48 @@ Your project may have a lot of log outputs, but you don't want to output everyth
731 792
732 Then Beego will not output log that has lower level of LevelWarning. Here is the list of all log levels, order from lower to higher: 793 Then Beego will not output log that has lower level of LevelWarning. Here is the list of all log levels, order from lower to higher:
733 794
734 LevelTrace、LevelDebug、LevelInfo、LevelWarning、 LevelError、LevelCritical 795 LevelTrace, LevelDebug, LevelInfo, LevelWarning, LevelError, LevelCritical
735 796
736 You can use different log level to output different error messages, it's based on how critical the error you think it is: 797 You can use different log level to output different error messages, it's based on how critical the error you think it is:
737 798
799
738 ### Examples of log messages 800 ### Examples of log messages
801
739 - Trace 802 - Trace
740 803
741 * "Entered parse function validation block" 804 * "Entered parse function validation block"
742 * "Validation: entered second 'if'" 805 * "Validation: entered second 'if'"
743 * "Dictionary 'Dict' is empty. Using default value" 806 * "Dictionary 'Dict' is empty. Using default value"
807
744 - Debug 808 - Debug
745 809
746 * "Web page requested: http://somesite.com Params='...'" 810 * "Web page requested: http://somesite.com Params='...'"
747 * "Response generated. Response size: 10000. Sending." 811 * "Response generated. Response size: 10000. Sending."
748 * "New file received. Type:PNG Size:20000" 812 * "New file received. Type:PNG Size:20000"
813
749 - Info 814 - Info
815
750 * "Web server restarted" 816 * "Web server restarted"
751 * "Hourly statistics: Requested pages: 12345 Errors: 123 ..." 817 * "Hourly statistics: Requested pages: 12345 Errors: 123 ..."
752 * "Service paused. Waiting for 'resume' call" 818 * "Service paused. Waiting for 'resume' call"
819
753 - Warn 820 - Warn
821
754 * "Cache corrupted for file='test.file'. Reading from back-end" 822 * "Cache corrupted for file='test.file'. Reading from back-end"
755 * "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB" 823 * "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
756 * "No response from statistics server. Statistics not sent" 824 * "No response from statistics server. Statistics not sent"
825
757 - Error 826 - Error
827
758 * "Internal error. Cannot process request #12345 Error:...." 828 * "Internal error. Cannot process request #12345 Error:...."
759 * "Cannot perform login: credentials DB not responding" 829 * "Cannot perform login: credentials DB not responding"
830
760 - Critical 831 - Critical
832
761 * "Critical panic received: .... Shutting down" 833 * "Critical panic received: .... Shutting down"
762 * "Fatal error: ... App is shutting down to prevent data corruption or loss" 834 * "Fatal error: ... App is shutting down to prevent data corruption or loss"
763 835
836
764 ### Example 837 ### Example
765 838
766 func internalCalculationFunc(x, y int) (result int, err error) { 839 func internalCalculationFunc(x, y int) (result int, err error) {
...@@ -827,7 +900,9 @@ You can use different log level to output different error messages, it's based o ...@@ -827,7 +900,9 @@ You can use different log level to output different error messages, it's based o
827 } 900 }
828 } 901 }
829 902
830 ##Configuration 903
904 ## Configuration
905
831 Beego supports to parse .ini file in path `conf/app.conf`, and you have following options: 906 Beego supports to parse .ini file in path `conf/app.conf`, and you have following options:
832 907
833 appname = beepkg 908 appname = beepkg
...@@ -862,7 +937,9 @@ AppConfig supports following methods: ...@@ -862,7 +937,9 @@ AppConfig supports following methods:
862 - Float(key string) (float64, error) 937 - Float(key string) (float64, error)
863 - String(key string) string 938 - String(key string) string
864 939
865 ##Beego arguments 940
941 ## Beego arguments
942
866 Beego has many configurable arguments, let me introduce to you all of them, so you can use them for more usage in your application: 943 Beego has many configurable arguments, let me introduce to you all of them, so you can use them for more usage in your application:
867 944
868 * BeeApp 945 * BeeApp
...@@ -944,7 +1021,9 @@ Beego has many configurable arguments, let me introduce to you all of them, so y ...@@ -944,7 +1021,9 @@ Beego has many configurable arguments, let me introduce to you all of them, so y
944 1021
945 This value indicate whether enable gzip or not, default is false. 1022 This value indicate whether enable gzip or not, default is false.
946 1023
947 ##Integrated third-party applications 1024
1025 ## Integrated third-party applications
1026
948 Beego supports to integrate third-party application, you can customized `http.Handler` as follows: 1027 Beego supports to integrate third-party application, you can customized `http.Handler` as follows:
949 1028
950 beego.RouterHandler("/chat/:info(.*)", sockjshandler) 1029 beego.RouterHandler("/chat/:info(.*)", sockjshandler)
...@@ -998,7 +1077,9 @@ Beego has an example for supporting chat of sockjs, here is the code: ...@@ -998,7 +1077,9 @@ Beego has an example for supporting chat of sockjs, here is the code:
998 1077
999 The above example implemented a simple chat room for sockjs, and you can use `http.Handler` for more extensions. 1078 The above example implemented a simple chat room for sockjs, and you can use `http.Handler` for more extensions.
1000 1079
1001 ##Deployment 1080
1081 ## Deployment
1082
1002 Go compiles program to binary file, you only need to copy this binary to your server and run it. Because Beego uses MVC model, so you may have folders for static files, configuration files and template files, so you have to copy those files as well. Here is a real example for deployment. 1083 Go compiles program to binary file, you only need to copy this binary to your server and run it. Because Beego uses MVC model, so you may have folders for static files, configuration files and template files, so you have to copy those files as well. Here is a real example for deployment.
1003 1084
1004 $ mkdir /opt/app/beepkg 1085 $ mkdir /opt/app/beepkg
......
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. Documentation and downloads available at [http://astaxie.github.com/beego](http://astaxie.github.com/beego)
3 4
4 It has following main features: 5 It has following main features:
...@@ -19,7 +20,9 @@ The working principles of Beego as follows: ...@@ -19,7 +20,9 @@ The working principles of Beego as follows:
19 Beego is licensed under the Apache Licence, Version 2.0 20 Beego is licensed under the Apache Licence, Version 2.0
20 (http://www.apache.org/licenses/LICENSE-2.0.html). 21 (http://www.apache.org/licenses/LICENSE-2.0.html).
21 22
22 #Simple example 23
24 # Simple example
25
23 The following example prints string "Hello world" to your browser, it shows how easy to build a web application with Beego. 26 The following example prints string "Hello world" to your browser, it shows how easy to build a web application with Beego.
24 27
25 package main 28 package main
...@@ -41,7 +44,9 @@ The following example prints string "Hello world" to your browser, it shows how ...@@ -41,7 +44,9 @@ The following example prints string "Hello world" to your browser, it shows how
41 beego.Run() 44 beego.Run()
42 } 45 }
43 46
44 #Handbook 47
48 # Handbook
49
45 - [Purposes](Why.md) 50 - [Purposes](Why.md)
46 - [Installation](Install.md) 51 - [Installation](Install.md)
47 - [Quick start](Quickstart.md) 52 - [Quick start](Quickstart.md)
...@@ -49,5 +54,7 @@ The following example prints string "Hello world" to your browser, it shows how ...@@ -49,5 +54,7 @@ The following example prints string "Hello world" to your browser, it shows how
49 - [Real world usage](Application.md) 54 - [Real world usage](Application.md)
50 - [Hot update](HotUpdate.md) 55 - [Hot update](HotUpdate.md)
51 56
52 #Documentation 57
58 # Documentation
59
53 [Go Walker](http://gowalker.org/github.com/astaxie/beego) 60 [Go Walker](http://gowalker.org/github.com/astaxie/beego)
......
1 ##supervisord 1 ## supervisord
2 2
3 1. Installation 3 1. Installation
4 4
......
1 # 一步一步跟我写博客 1 # 一步一步跟我写博客
2 2
3
3 ## 创建项目 4 ## 创建项目
4 5
6
5 ## 数据库结构设计 7 ## 数据库结构设计
6 8
9
7 ## 控制器设计 10 ## 控制器设计
8 11
12
9 ## 模板设计 13 ## 模板设计
10 14
15
11 ## 用户登陆退出 16 ## 用户登陆退出
12 17
18
13 ## 数据库操作 19 ## 数据库操作
......
1 # Design purposes and ideas 1 # Design purposes and ideas
2
2 People may ask me why I want to build a new web framework rather than use other good ones. I know there are many excellent web frameworks on the internet and almost all of them are open source, and I have my reasons to do this. 3 People may ask me why I want to build a new web framework rather than use other good ones. I know there are many excellent web frameworks on the internet and almost all of them are open source, and I have my reasons to do this.
3 4
4 Remember when I was writing the book about how to build web applications with Go, I just wanted to tell people what were my valuable experiences with Go in web development, especially I have been working with PHP and Python for almost ten years. At first, I didn't realize that a small web framework can give great help to web developers when they are learning to build web applications in a new programming language, and it also helps people more by studying its source code. Finally, I decided to write a open source web framework called Beego as supporting materiel for my book. 5 Remember when I was writing the book about how to build web applications with Go, I just wanted to tell people what were my valuable experiences with Go in web development, especially I have been working with PHP and Python for almost ten years. At first, I didn't realize that a small web framework can give great help to web developers when they are learning to build web applications in a new programming language, and it also helps people more by studying its source code. Finally, I decided to write a open source web framework called Beego as supporting materiel for my book.
...@@ -9,7 +10,7 @@ I used to use CI in PHP and tornado in Python, there are both lightweight, so th ...@@ -9,7 +10,7 @@ I used to use CI in PHP and tornado in Python, there are both lightweight, so th
9 2. Learn more about languages by studying their source code, it's not hard to read and understand them because they are both lightweight frameworks. 10 2. Learn more about languages by studying their source code, it's not hard to read and understand them because they are both lightweight frameworks.
10 3. It's quite easy to make secondary development of these frameworks for specific purposes. 11 3. It's quite easy to make secondary development of these frameworks for specific purposes.
11 12
12 Those reasons are my original intention of implementing Beego, and used two chapters in my book to introduce and design this lightweight web framework in GO. 13 Those reasons are my original intention of implementing Beego, and used two chapters in my book to introduce and design this lightweight web framework in Go.
13 14
14 Then I started to design logic execution of Beego. Because Go and Python have somewhat similar, I referenced some ideas from tornado to design Beego. As you can see, there is no different between Beego and tornado in RESTful processing; they both use GET, POST or some other methods to implement RESTful. I took some ideas from [https://github.com/drone/routes](https://github.com/drone/routes) at the beginning of designing routes. It uses regular expression in route rules processing, which is an excellent idea that to make up for the default Mux router function in Go. However, I have to design my own interface in order to implement RESTful and use inherited ideas in Python. 15 Then I started to design logic execution of Beego. Because Go and Python have somewhat similar, I referenced some ideas from tornado to design Beego. As you can see, there is no different between Beego and tornado in RESTful processing; they both use GET, POST or some other methods to implement RESTful. I took some ideas from [https://github.com/drone/routes](https://github.com/drone/routes) at the beginning of designing routes. It uses regular expression in route rules processing, which is an excellent idea that to make up for the default Mux router function in Go. However, I have to design my own interface in order to implement RESTful and use inherited ideas in Python.
15 16
......
...@@ -2,10 +2,12 @@ ...@@ -2,10 +2,12 @@
2 2
3 热升级是什么呢?了解nginx的同学都知道,nginx是支持热升级的,可以用老进程服务先前链接的链接,使用新进程服务新的链接,即在不停止服务的情况下完成系统的升级与运行参数修改。那么热升级和热编译是不同的概念,热编译是通过监控文件的变化重新编译,然后重启进程,例如bee start就是这样的工具 3 热升级是什么呢?了解nginx的同学都知道,nginx是支持热升级的,可以用老进程服务先前链接的链接,使用新进程服务新的链接,即在不停止服务的情况下完成系统的升级与运行参数修改。那么热升级和热编译是不同的概念,热编译是通过监控文件的变化重新编译,然后重启进程,例如bee start就是这样的工具
4 4
5
5 ## 热升级有必要吗? 6 ## 热升级有必要吗?
6 7
7 很多人认为HTTP的应用有必要支持热升级吗?那么我可以很负责的说非常有必要,不中断服务始终是我们所追求的目标,虽然很多人说可能服务器会坏掉等等,这个是属于高可用的设计范畴,不要搞混了,这个是可预知的问题,所以我们需要避免这样的升级带来的用户不可用。你还在为以前升级搞到凌晨升级而烦恼嘛?那么现在就赶紧拥抱热升级吧。 8 很多人认为HTTP的应用有必要支持热升级吗?那么我可以很负责的说非常有必要,不中断服务始终是我们所追求的目标,虽然很多人说可能服务器会坏掉等等,这个是属于高可用的设计范畴,不要搞混了,这个是可预知的问题,所以我们需要避免这样的升级带来的用户不可用。你还在为以前升级搞到凌晨升级而烦恼嘛?那么现在就赶紧拥抱热升级吧。
8 9
10
9 ## beego如何支持热升级 11 ## beego如何支持热升级
10 热升级的原理基本上就是:主进程fork一个进程,然后子进程exec相应的程序。那么这个过程中发生了什么呢?我们知道进程fork之后会把主进程的所有句柄、数据和堆栈继承过来、但是里面所有的句柄存在一个叫做CloseOnExec,也就是执行exec的时候,copy的所有的句柄都被关闭了,除非特别申明,而我们期望的是子进程能够复用主进程的net.Listener的句柄。一个进程一旦调用exec类函数,它本身就"死亡"了,系统把代码段替换成新的程序的代码,废弃原有的数据段和堆栈段,并为新程序分配新的数据段与堆栈段,唯一留下的,就是进程号,也就是说,对系统而言,还是同一个进程,不过已经是另一个程序了。 12 热升级的原理基本上就是:主进程fork一个进程,然后子进程exec相应的程序。那么这个过程中发生了什么呢?我们知道进程fork之后会把主进程的所有句柄、数据和堆栈继承过来、但是里面所有的句柄存在一个叫做CloseOnExec,也就是执行exec的时候,copy的所有的句柄都被关闭了,除非特别申明,而我们期望的是子进程能够复用主进程的net.Listener的句柄。一个进程一旦调用exec类函数,它本身就"死亡"了,系统把代码段替换成新的程序的代码,废弃原有的数据段和堆栈段,并为新程序分配新的数据段与堆栈段,唯一留下的,就是进程号,也就是说,对系统而言,还是同一个进程,不过已经是另一个程序了。
11 13
...@@ -17,6 +19,7 @@ ...@@ -17,6 +19,7 @@
17 19
18 上面是我们需要解决的三个方面的问题,具体的实现大家可以看我实现的代码逻辑。 20 上面是我们需要解决的三个方面的问题,具体的实现大家可以看我实现的代码逻辑。
19 21
22
20 ## 如何演示热升级 23 ## 如何演示热升级
21 24
22 1. 编写代码,在beego应用的控制器中Get方法实现大概如下: 25 1. 编写代码,在beego应用的控制器中Get方法实现大概如下:
......
1 # 安装入门 1 # 安装入门
2
2 beego虽然是一个简单的框架,但是其中用到了很多第三方的包,所以在你安装beego的过程中Go会自动安装其他关联的包。 3 beego虽然是一个简单的框架,但是其中用到了很多第三方的包,所以在你安装beego的过程中Go会自动安装其他关联的包。
3 4
4 - 当然第一步你需要安装Go,如何安装Go请参考我的书[第一章](https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/01.1.md) 5 - 当然第一步你需要安装Go,如何安装Go请参考我的书[第一章](https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/01.1.md)
...@@ -19,6 +20,7 @@ beego虽然是一个简单的框架,但是其中用到了很多第三方的包 ...@@ -19,6 +20,7 @@ beego虽然是一个简单的框架,但是其中用到了很多第三方的包
19 20
20 > - session模块:github.com/astaxie/beego/session 21 > - session模块:github.com/astaxie/beego/session
21 22
23
22 > - session模块中支持redis引擎:github.com/garyburd/redigo/redis 24 > - session模块中支持redis引擎:github.com/garyburd/redigo/redis
23 25
24 > - session模块中支持mysql引擎:github.com/go-sql-driver/mysql 26 > - session模块中支持mysql引擎:github.com/go-sql-driver/mysql
......
1 # 快速入门 1 # 快速入门
2
2 你对beego一无所知?没关系,这篇文档会很好的详细介绍beego的各个方面,看这个文档之前首先确认你已经安装了beego,如果你没有安装的话,请看这篇[安装指南](Install.md) 3 你对beego一无所知?没关系,这篇文档会很好的详细介绍beego的各个方面,看这个文档之前首先确认你已经安装了beego,如果你没有安装的话,请看这篇[安装指南](Install.md)
3 4
4 **导航** 5 **导航**
...@@ -23,7 +24,9 @@ ...@@ -23,7 +24,9 @@
23 - [第三方应用集成](#-19) 24 - [第三方应用集成](#-19)
24 - [部署编译应用](#-20) 25 - [部署编译应用](#-20)
25 26
27
26 ## 最小应用 28 ## 最小应用
29
27 一个最小最简单的应用如下代码所示: 30 一个最小最简单的应用如下代码所示:
28 31
29 package main 32 package main
...@@ -68,6 +71,7 @@ ...@@ -68,6 +71,7 @@
68 71
69 停止服务的话,请按`ctrl+c` 72 停止服务的话,请按`ctrl+c`
70 73
74
71 ## 新建项目 75 ## 新建项目
72 76
73 通过如下命令创建beego项目,首先进入gopath目录 77 通过如下命令创建beego项目,首先进入gopath目录
...@@ -90,6 +94,7 @@ ...@@ -90,6 +94,7 @@
90 └── views 94 └── views
91 └── index.tpl 95 └── index.tpl
92 96
97
93 ## 开发模式 98 ## 开发模式
94 99
95 通过bee创建的项目,beego默认情况下是开发模式。 100 通过bee创建的项目,beego默认情况下是开发模式。
...@@ -115,6 +120,7 @@ ...@@ -115,6 +120,7 @@
115 120
116 ![](images/dev.png) 121 ![](images/dev.png)
117 122
123
118 ## 路由设置 124 ## 路由设置
119 125
120 路由的主要功能是实现从请求地址到实现方法,beego中封装了`Controller`,所以路由是从路径到`ControllerInterface`的过程,`ControllerInterface`的方法有如下: 126 路由的主要功能是实现从请求地址到实现方法,beego中封装了`Controller`,所以路由是从路径到`ControllerInterface`的过程,`ControllerInterface`的方法有如下:
...@@ -173,7 +179,9 @@ ...@@ -173,7 +179,9 @@
173 this.Ctx.Params[":path"] 179 this.Ctx.Params[":path"]
174 this.Ctx.Params[":ext"] 180 this.Ctx.Params[":ext"]
175 181
182
176 ## 静态文件 183 ## 静态文件
184
177 Go语言内部其实已经提供了`http.ServeFile`,通过这个函数可以实现静态文件的服务。beego针对这个功能进行了一层封装,通过下面的方式进行静态文件注册: 185 Go语言内部其实已经提供了`http.ServeFile`,通过这个函数可以实现静态文件的服务。beego针对这个功能进行了一层封装,通过下面的方式进行静态文件注册:
178 186
179 beego.SetStaticPath("/static","public") 187 beego.SetStaticPath("/static","public")
...@@ -189,7 +197,9 @@ beego葵敶辣瘜典隞交釣 ...@@ -189,7 +197,9 @@ beego葵敶辣瘜典隞交釣
189 197
190 设置了如上的静态目录之后,用户访问`/images/login/login.png`,那么就会访问应用对应的目录下面的`images/login/login.png`文件。如果是访问`/static/img/logo.png`,那么就访问`public/img/logo.png`文件。 198 设置了如上的静态目录之后,用户访问`/images/login/login.png`,那么就会访问应用对应的目录下面的`images/login/login.png`文件。如果是访问`/static/img/logo.png`,那么就访问`public/img/logo.png`文件。
191 199
200
192 ## 过滤和中间件 201 ## 过滤和中间件
202
193 beego支持自定义过滤中间件,例如安全验证,强制跳转等 203 beego支持自定义过滤中间件,例如安全验证,强制跳转等
194 204
195 如下例子所示,验证用户名是否是admin,应用于全部的请求: 205 如下例子所示,验证用户名是否是admin,应用于全部的请求:
...@@ -215,7 +225,9 @@ beego摰誘銝剝隞塚撉撩頝唾蓮蝑 ...@@ -215,7 +225,9 @@ beego摰誘銝剝隞塚撉撩頝唾蓮蝑
215 dosomething() 225 dosomething()
216 }) 226 })
217 227
228
218 ## 控制器设计 229 ## 控制器设计
230
219 基于beego的Controller设计,只需要匿名组合`beego.Controller`就可以了,如下所示: 231 基于beego的Controller设计,只需要匿名组合`beego.Controller`就可以了,如下所示:
220 232
221 type xxxController struct { 233 type xxxController struct {
...@@ -279,7 +291,7 @@ beego摰誘銝剝隞塚撉撩頝唾蓮蝑 ...@@ -279,7 +291,7 @@ beego摰誘銝剝隞塚撉撩頝唾蓮蝑
279 } 291 }
280 292
281 func (this *AddController) Get() { 293 func (this *AddController) Get() {
282 this.Data["content"] ="value" 294 this.Data["content"] = "value"
283 this.Layout = "admin/layout.html" 295 this.Layout = "admin/layout.html"
284 this.TplNames = "admin/add.tpl" 296 this.TplNames = "admin/add.tpl"
285 } 297 }
...@@ -303,12 +315,19 @@ beego摰誘銝剝隞塚撉撩頝唾蓮蝑 ...@@ -303,12 +315,19 @@ beego摰誘銝剝隞塚撉撩頝唾蓮蝑
303 this.Ctx.Redirect(302, "/admin/index") 315 this.Ctx.Redirect(302, "/admin/index")
304 } 316 }
305 317
318
306 ## 模板处理 319 ## 模板处理
320
321
307 ### 模板目录 322 ### 模板目录
323
308 beego中默认的模板目录是`views`,用户可以把你的模板文件放到该目录下,beego会自动在该目录下的所有模板文件进行解析并缓存,开发模式下会每次重新解析,不做缓存。当然用户可以通过如下的方式改变模板的目录: 324 beego中默认的模板目录是`views`,用户可以把你的模板文件放到该目录下,beego会自动在该目录下的所有模板文件进行解析并缓存,开发模式下会每次重新解析,不做缓存。当然用户可以通过如下的方式改变模板的目录:
309 325
310 beego.ViewsPath = "/myviewpath" 326 beego.ViewsPath = "/myviewpath"
327
328
311 ### 自动渲染 329 ### 自动渲染
330
312 beego中用户无需手动的调用渲染输出模板,beego会自动的在调用完相应的method方法之后调用Render函数,当然如果你的应用是不需要模板输出的,那么你可以在配置文件或者在main.go中设置关闭自动渲染。 331 beego中用户无需手动的调用渲染输出模板,beego会自动的在调用完相应的method方法之后调用Render函数,当然如果你的应用是不需要模板输出的,那么你可以在配置文件或者在main.go中设置关闭自动渲染。
313 332
314 配置文件配置如下: 333 配置文件配置如下:
...@@ -319,12 +338,16 @@ main.go辣銝剛挽蝵桀 ...@@ -319,12 +338,16 @@ main.go辣銝剛挽蝵桀
319 338
320 beego.AutoRender = false 339 beego.AutoRender = false
321 340
341
322 ### 模板数据 342 ### 模板数据
343
323 模板中的数据是通过在Controller中`this.Data`获取的,所以如果你想在模板中获取内容`{{.Content}}`,那么你需要在Controller中如下设置: 344 模板中的数据是通过在Controller中`this.Data`获取的,所以如果你想在模板中获取内容`{{.Content}}`,那么你需要在Controller中如下设置:
324 345
325 this.Data["Context"] = "value" 346 this.Data["Context"] = "value"
326 347
348
327 ### 模板名称 349 ### 模板名称
350
328 beego采用了Go语言内置的模板引擎,所有模板的语法和Go的一模一样,至于如何写模板文件,详细的请参考[模板教程](https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/07.4.md) 351 beego采用了Go语言内置的模板引擎,所有模板的语法和Go的一模一样,至于如何写模板文件,详细的请参考[模板教程](https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/07.4.md)
329 352
330 用户通过在Controller的对应方法中设置相应的模板名称,beego会自动的在viewpath目录下查询该文件并渲染,例如下面的设置,beego会在admin下面找add.tpl文件进行渲染: 353 用户通过在Controller的对应方法中设置相应的模板名称,beego会自动的在viewpath目录下查询该文件并渲染,例如下面的设置,beego会在admin下面找add.tpl文件进行渲染:
...@@ -341,7 +364,9 @@ beego鈭o霂剛蔭芋撘芋祗瘜o璅 ...@@ -341,7 +364,9 @@ beego鈭o霂剛蔭芋撘芋祗瘜o璅
341 364
342 也就是你对应的Controller名字+请求方法名.模板后缀,也就是如果你的Controller名是`AddController`,请求方法是`POST`,默认的文件后缀是`tpl`,那么就会默认请求`/viewpath/AddController/POST.tpl`文件。 365 也就是你对应的Controller名字+请求方法名.模板后缀,也就是如果你的Controller名是`AddController`,请求方法是`POST`,默认的文件后缀是`tpl`,那么就会默认请求`/viewpath/AddController/POST.tpl`文件。
343 366
367
344 ### layout设计 368 ### layout设计
369
345 beego支持layout设计,例如你在管理系统中,其实整个的管理界面是固定的,只会变化中间的部分,那么你可以通过如下的设置: 370 beego支持layout设计,例如你在管理系统中,其实整个的管理界面是固定的,只会变化中间的部分,那么你可以通过如下的设置:
346 371
347 this.Layout = "admin/layout.html" 372 this.Layout = "admin/layout.html"
...@@ -359,7 +384,9 @@ beego撠曹圾plNames辣嚗捆韏潛ayoutCont ...@@ -359,7 +384,9 @@ beego撠曹圾plNames辣嚗捆韏潛ayoutCont
359 处理逻辑 384 处理逻辑
360 {{template "footer.html"}} 385 {{template "footer.html"}}
361 386
387
362 ### 模板函数 388 ### 模板函数
389
363 beego支持用户定义模板函数,但是必须在`beego.Run()`调用之前,设置如下: 390 beego支持用户定义模板函数,但是必须在`beego.Run()`调用之前,设置如下:
364 391
365 func hello(in string)(out string){ 392 func hello(in string)(out string){
...@@ -378,32 +405,42 @@ beego摰芋嚗敹◆`beego.Run()`靚銋 ...@@ -378,32 +405,42 @@ beego摰芋嚗敹◆`beego.Run()`靚銋
378 * markdown 405 * markdown
379 406
380 实现了把markdown文本转化为html信息,使用方法{{markdown .Content}} 407 实现了把markdown文本转化为html信息,使用方法{{markdown .Content}}
408
381 * dateformat 409 * dateformat
382 410
383 实现了时间的格式化,返回字符串,使用方法{{dateformat .Time "2006-01-02T15:04:05Z07:00"}} 411 实现了时间的格式化,返回字符串,使用方法{{dateformat .Time "2006-01-02T15:04:05Z07:00"}}
412
384 * date 413 * date
385 414
386 实现了类似PHP的date函数,可以很方便的根据字符串返回时间,使用方法{{date .T "Y-m-d H:i:s"}} 415 实现了类似PHP的date函数,可以很方便的根据字符串返回时间,使用方法{{date .T "Y-m-d H:i:s"}}
416
387 * compare 417 * compare
388 418
389 实现了比较两个对象的比较,如果相同返回true,否者false,使用方法{{compare .A .B}} 419 实现了比较两个对象的比较,如果相同返回true,否者false,使用方法{{compare .A .B}}
420
390 * substr 421 * substr
391 422
392 实现了字符串的截取,支持中文截取的完美截取,使用方法{{substr .Str 0 30}} 423 实现了字符串的截取,支持中文截取的完美截取,使用方法{{substr .Str 0 30}}
424
393 * html2str 425 * html2str
394 426
395 实现了把html转化为字符串,剔除一些script、css之类的元素,返回纯文本信息,使用方法{{html2str .Htmlinfo}} 427 实现了把html转化为字符串,剔除一些script、css之类的元素,返回纯文本信息,使用方法{{html2str .Htmlinfo}}
428
396 * str2html 429 * str2html
397 430
398 实现了把相应的字符串当作HTML来输出,不转义,使用方法{{str2html .Strhtml}} 431 实现了把相应的字符串当作HTML来输出,不转义,使用方法{{str2html .Strhtml}}
432
399 * htmlquote 433 * htmlquote
400 434
401 实现了基本的html字符转义,使用方法{{htmlquote .quote}} 435 实现了基本的html字符转义,使用方法{{htmlquote .quote}}
436
402 * htmlunquote 437 * htmlunquote
403 438
404 实现了基本的反转移字符,使用方法{{htmlunquote .unquote}} 439 实现了基本的反转移字符,使用方法{{htmlunquote .unquote}}
405 440
441
406 ## request处理 442 ## request处理
443
407 我们经常需要获取用户传递的数据,包括Get、POST等方式的请求,beego里面会自动解析这些数据,你可以通过如下方式获取数据 444 我们经常需要获取用户传递的数据,包括Get、POST等方式的请求,beego里面会自动解析这些数据,你可以通过如下方式获取数据
408 445
409 - GetString(key string) string 446 - GetString(key string) string
...@@ -429,7 +466,9 @@ beego摰芋嚗敹◆`beego.Run()`靚銋 ...@@ -429,7 +466,9 @@ beego摰芋嚗敹◆`beego.Run()`靚銋
429 466
430 更多其他的request的信息,用户可以通过`this.Ctx.Request`获取信息,关于该对象的属性和方法参考手册[Request](http://golang.org/pkg/net/http/#Request) 467 更多其他的request的信息,用户可以通过`this.Ctx.Request`获取信息,关于该对象的属性和方法参考手册[Request](http://golang.org/pkg/net/http/#Request)
431 468
469
432 ### 文件上传 470 ### 文件上传
471
433 在beego中你可以很容易的处理文件上传,就是别忘记在你的form表单中增加这个属性`enctype="multipart/form-data"`,否者你的浏览器不会传输你的上传文件。 472 在beego中你可以很容易的处理文件上传,就是别忘记在你的form表单中增加这个属性`enctype="multipart/form-data"`,否者你的浏览器不会传输你的上传文件。
434 473
435 文件上传之后一般是放在系统的内存里面,如果文件的size大于设置的缓存内存大小,那么就放在临时文件中,默认的缓存内存是64M,你可以通过如下来调整这个缓存内存大小: 474 文件上传之后一般是放在系统的内存里面,如果文件的size大于设置的缓存内存大小,那么就放在临时文件中,默认的缓存内存是64M,你可以通过如下来调整这个缓存内存大小:
...@@ -456,7 +495,9 @@ beego舅銝芸靘輻瘜憭辣銝 ...@@ -456,7 +495,9 @@ beego舅銝芸靘輻瘜憭辣銝
456 this.SaveToFile("the_file","/var/www/uploads/uploaded_file.txt"") 495 this.SaveToFile("the_file","/var/www/uploads/uploaded_file.txt"")
457 } 496 }
458 497
498
459 ### JSON和XML输出 499 ### JSON和XML输出
500
460 beego当初设计的时候就考虑了API功能的设计,而我们在设计API的时候经常是输出JSON或者XML数据,那么beego提供了这样的方式直接输出: 501 beego当初设计的时候就考虑了API功能的设计,而我们在设计API的时候经常是输出JSON或者XML数据,那么beego提供了这样的方式直接输出:
461 502
462 JSON数据直接输出,设置`content-type``application/json` 503 JSON数据直接输出,设置`content-type``application/json`
...@@ -475,7 +516,9 @@ XML颲嚗挽蝵害content-type`銝槁application/xml`嚗 ...@@ -475,7 +516,9 @@ XML颲嚗挽蝵害content-type`銝槁application/xml`嚗
475 this.ServeXml() 516 this.ServeXml()
476 } 517 }
477 518
519
478 ## 跳转和错误 520 ## 跳转和错误
521
479 我们在做Web开发的时候,经常会遇到页面调整和错误处理,beego这这方面也进行了考虑,通过`Redirect`方法来进行跳转: 522 我们在做Web开发的时候,经常会遇到页面调整和错误处理,beego这这方面也进行了考虑,通过`Redirect`方法来进行跳转:
480 523
481 func (this *AddController) Get() { 524 func (this *AddController) Get() {
...@@ -535,7 +578,9 @@ beego犖批銝芾挽霈∪停摰泵銝脤 ...@@ -535,7 +578,9 @@ beego犖批銝芾挽霈∪停摰泵銝脤
535 578
536 一旦在入口注册该错误处理代码,那么你可以在任何你的逻辑中遇到数据库错误调用`this.Abort("dbError")`来进行异常页面处理。 579 一旦在入口注册该错误处理代码,那么你可以在任何你的逻辑中遇到数据库错误调用`this.Abort("dbError")`来进行异常页面处理。
537 580
581
538 ## response处理 582 ## response处理
583
539 response可能会有集中情况: 584 response可能会有集中情况:
540 585
541 1. 模板输出 586 1. 模板输出
...@@ -552,7 +597,9 @@ response隡葉嚗 ...@@ -552,7 +597,9 @@ response隡葉嚗
552 597
553 this.Ctx.WriteString("ok") 598 this.Ctx.WriteString("ok")
554 599
600
555 ## Sessions 601 ## Sessions
602
556 beego内置了session模块,目前session模块支持的后端引擎包括memory、file、mysql、redis四中,用户也可以根据相应的interface实现自己的引擎。 603 beego内置了session模块,目前session模块支持的后端引擎包括memory、file、mysql、redis四中,用户也可以根据相应的interface实现自己的引擎。
557 604
558 beego中使用session相当方便,只要在main入口函数中设置如下: 605 beego中使用session相当方便,只要在main入口函数中设置如下:
...@@ -637,7 +684,9 @@ sess撖寡情瘜 ...@@ -637,7 +684,9 @@ sess撖寡情瘜
637 beego.SessionProvider = "redis" 684 beego.SessionProvider = "redis"
638 beego.SessionSavePath = "127.0.0.1:6379" 685 beego.SessionSavePath = "127.0.0.1:6379"
639 686
687
640 ## Cache设置 688 ## Cache设置
689
641 beego内置了一个cache模块,实现了类似memcache的功能,缓存数据在内存中,主要的使用方法如下: 690 beego内置了一个cache模块,实现了类似memcache的功能,缓存数据在内存中,主要的使用方法如下:
642 691
643 var ( 692 var (
...@@ -681,7 +730,9 @@ beego蔭鈭銝泌ache璅∪鈭掩隡幟emcache嚗 ...@@ -681,7 +730,9 @@ beego蔭鈭銝泌ache璅∪鈭掩隡幟emcache嚗
681 - Delete(name string) (ok bool, err error) 730 - Delete(name string) (ok bool, err error)
682 - IsExist(name string) bool 731 - IsExist(name string) bool
683 732
733
684 ## 安全的Map 734 ## 安全的Map
735
685 我们知道在Go语言里面map是非线程安全的,详细的[atomic_maps](http://golang.org/doc/faq#atomic_maps)。但是我们在平常的业务中经常需要用到线程安全的map,特别是在goroutine的情况下,所以beego内置了一个简单的线程安全的map: 736 我们知道在Go语言里面map是非线程安全的,详细的[atomic_maps](http://golang.org/doc/faq#atomic_maps)。但是我们在平常的业务中经常需要用到线程安全的map,特别是在goroutine的情况下,所以beego内置了一个简单的线程安全的map:
686 737
687 bm := NewBeeMap() 738 bm := NewBeeMap()
...@@ -708,7 +759,9 @@ beego蔭鈭銝泌ache璅∪鈭掩隡幟emcache嚗 ...@@ -708,7 +759,9 @@ beego蔭鈭銝泌ache璅∪鈭掩隡幟emcache嚗
708 - Check(k interface{}) bool 759 - Check(k interface{}) bool
709 - Delete(k interface{}) 760 - Delete(k interface{})
710 761
762
711 ## 日志处理 763 ## 日志处理
764
712 beego默认有一个初始化的BeeLogger对象输出内容到stdout中,你可以通过如下的方式设置自己的输出: 765 beego默认有一个初始化的BeeLogger对象输出内容到stdout中,你可以通过如下的方式设置自己的输出:
713 766
714 beego.SetLogger(*log.Logger) 767 beego.SetLogger(*log.Logger)
...@@ -722,6 +775,8 @@ beego暺恕銝芸eeLogger撖寡情颲捆stdout銝哨 ...@@ -722,6 +775,8 @@ beego暺恕銝芸eeLogger撖寡情颲捆stdout銝哨
722 } 775 }
723 lg := log.New(fd, "", log.Ldate|log.Ltime) 776 lg := log.New(fd, "", log.Ldate|log.Ltime)
724 beego.SetLogger(lg) 777 beego.SetLogger(lg)
778
779
725 ### 不同级别的log日志函数 780 ### 不同级别的log日志函数
726 781
727 * Trace(v ...interface{}) 782 * Trace(v ...interface{})
...@@ -741,56 +796,68 @@ beego暺恕銝芸eeLogger撖寡情颲捆stdout銝哨 ...@@ -741,56 +796,68 @@ beego暺恕銝芸eeLogger撖寡情颲捆stdout銝哨
741 796
742 这样的话就不会输出小于这个level的日志,日志的排序如下: 797 这样的话就不会输出小于这个level的日志,日志的排序如下:
743 798
744 LevelTrace、LevelDebug、LevelInfo、LevelWarning、 LevelError、LevelCritical 799 LevelTrace、LevelDebug、LevelInfo、LevelWarning、LevelError、LevelCritical
745 800
746 用户可以根据不同的级别输出不同的错误信息,如下例子所示: 801 用户可以根据不同的级别输出不同的错误信息,如下例子所示:
747 802
803
748 ### Examples of log messages 804 ### Examples of log messages
805
749 - Trace 806 - Trace
750 807
751 * "Entered parse function validation block" 808 * "Entered parse function validation block"
752 * "Validation: entered second 'if'" 809 * "Validation: entered second 'if'"
753 * "Dictionary 'Dict' is empty. Using default value" 810 * "Dictionary 'Dict' is empty. Using default value"
811
754 - Debug 812 - Debug
755 813
756 * "Web page requested: http://somesite.com Params='...'" 814 * "Web page requested: http://somesite.com Params='...'"
757 * "Response generated. Response size: 10000. Sending." 815 * "Response generated. Response size: 10000. Sending."
758 * "New file received. Type:PNG Size:20000" 816 * "New file received. Type:PNG Size:20000"
817
759 - Info 818 - Info
819
760 * "Web server restarted" 820 * "Web server restarted"
761 * "Hourly statistics: Requested pages: 12345 Errors: 123 ..." 821 * "Hourly statistics: Requested pages: 12345 Errors: 123 ..."
762 * "Service paused. Waiting for 'resume' call" 822 * "Service paused. Waiting for 'resume' call"
823
763 - Warn 824 - Warn
825
764 * "Cache corrupted for file='test.file'. Reading from back-end" 826 * "Cache corrupted for file='test.file'. Reading from back-end"
765 * "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB" 827 * "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
766 * "No response from statistics server. Statistics not sent" 828 * "No response from statistics server. Statistics not sent"
829
767 - Error 830 - Error
831
768 * "Internal error. Cannot process request #12345 Error:...." 832 * "Internal error. Cannot process request #12345 Error:...."
769 * "Cannot perform login: credentials DB not responding" 833 * "Cannot perform login: credentials DB not responding"
834
770 - Critical 835 - Critical
836
771 * "Critical panic received: .... Shutting down" 837 * "Critical panic received: .... Shutting down"
772 * "Fatal error: ... App is shutting down to prevent data corruption or loss" 838 * "Fatal error: ... App is shutting down to prevent data corruption or loss"
773 839
840
774 ### Example 841 ### Example
775 842
776 func internalCalculationFunc(x, y int) (result int, err error) { 843 func internalCalculationFunc(x, y int) (result int, err error) {
777 beego.Debug("calculating z. x:",x," y:",y) 844 beego.Debug("calculating z. x:", x, " y:", y)
778 z := y 845 z := y
779 switch { 846 switch {
780 case x == 3 : 847 case x == 3:
781 beego.Trace("x == 3") 848 beego.Trace("x == 3")
782 panic("Failure.") 849 panic("Failure.")
783 case y == 1 : 850 case y == 1:
784 beego.Trace("y == 1") 851 beego.Trace("y == 1")
785 return 0, errors.New("Error!") 852 return 0, errors.New("Error!")
786 case y == 2 : 853 case y == 2:
787 beego.Trace("y == 2") 854 beego.Trace("y == 2")
788 z = x 855 z = x
789 default : 856 default:
790 beego.Trace("default") 857 beego.Trace("default")
791 z += x 858 z += x
792 } 859 }
793 retVal := z-3 860 retVal := z - 3
794 beego.Debug("Returning ", retVal) 861 beego.Debug("Returning ", retVal)
795 862
796 return retVal, nil 863 return retVal, nil
...@@ -800,18 +867,18 @@ LevelTraceevelDebugevelInfoevelWarning LevelErrorevelCritical ...@@ -800,18 +867,18 @@ LevelTraceevelDebugevelInfoevelWarning LevelErrorevelCritical
800 defer func() { 867 defer func() {
801 if r := recover(); r != nil { 868 if r := recover(); r != nil {
802 beego.Error("Unexpected error occurred: ", r) 869 beego.Error("Unexpected error occurred: ", r)
803 outputs <- outputData{result : 0, error : true} 870 outputs <- outputData{result: 0, error: true}
804 } 871 }
805 }() 872 }()
806 beego.Info("Received input signal. x:",input.x," y:", input.y) 873 beego.Info("Received input signal. x:", input.x, " y:", input.y)
807 874
808 res, err := internalCalculationFunc(input.x, input.y) 875 res, err := internalCalculationFunc(input.x, input.y)
809 if err != nil { 876 if err != nil {
810 beego.Warn("Error in calculation:", err.Error()) 877 beego.Warn("Error in calculation:", err.Error())
811 } 878 }
812 879
813 beego.Info("Returning result: ",res," error: ",err) 880 beego.Info("Returning result: ", res, " error: ", err)
814 outputs <- outputData{result : res, error : err != nil} 881 outputs <- outputData{result: res, error: err != nil}
815 } 882 }
816 883
817 func main() { 884 func main() {
...@@ -828,16 +895,18 @@ LevelTraceevelDebugevelInfoevelWarning LevelErrorevelCritical ...@@ -828,16 +895,18 @@ LevelTraceevelDebugevelInfoevelWarning LevelErrorevelCritical
828 895
829 for { 896 for {
830 select { 897 select {
831 case input := <- inputs: 898 case input := <-inputs:
832 processInput(input) 899 processInput(input)
833 case <- criticalChan: 900 case <-criticalChan:
834 beego.Critical("Caught value from criticalChan: Go shut down.") 901 beego.Critical("Caught value from criticalChan: Go shut down.")
835 panic("Shut down due to critical fault.") 902 panic("Shut down due to critical fault.")
836 } 903 }
837 } 904 }
838 } 905 }
839 906
907
840 ## 配置管理 908 ## 配置管理
909
841 beego支持解析ini文件, beego默认会解析当前应用下的`conf/app.conf`文件 910 beego支持解析ini文件, beego默认会解析当前应用下的`conf/app.conf`文件
842 911
843 通过这个文件你可以初始化很多beego的默认参数 912 通过这个文件你可以初始化很多beego的默认参数
...@@ -874,7 +943,9 @@ AppConfig瘜 ...@@ -874,7 +943,9 @@ AppConfig瘜
874 - Float(key string) (float64, error) 943 - Float(key string) (float64, error)
875 - String(key string) string 944 - String(key string) string
876 945
946
877 ## 系统默认参数 947 ## 系统默认参数
948
878 beego中带有很多可配置的参数,我们来一一认识一下它们,这样有利于我们在接下来的beego开发中可以充分的发挥他们的作用: 949 beego中带有很多可配置的参数,我们来一一认识一下它们,这样有利于我们在接下来的beego开发中可以充分的发挥他们的作用:
879 950
880 * BeeApp 951 * BeeApp
...@@ -959,7 +1030,9 @@ beego銝剖蒂蔭嚗賑銝銝霈方銝賑嚗 ...@@ -959,7 +1030,9 @@ beego銝剖蒂蔭嚗賑銝銝霈方銝賑嚗
959 1030
960 是否开启gzip支持,默认为false不支持gzip,一旦开启了gzip,那么在模板输出的内容会进行gzip或者zlib压缩,根据用户的Accept-Encoding来判断。 1031 是否开启gzip支持,默认为false不支持gzip,一旦开启了gzip,那么在模板输出的内容会进行gzip或者zlib压缩,根据用户的Accept-Encoding来判断。
961 1032
1033
962 ## 第三方应用集成 1034 ## 第三方应用集成
1035
963 beego支持第三方应用的集成,用户可以自定义`http.Handler`,用户可以通过如下方式进行注册路由: 1036 beego支持第三方应用的集成,用户可以自定义`http.Handler`,用户可以通过如下方式进行注册路由:
964 1037
965 beego.RouterHandler("/chat/:info(.*)", sockjshandler) 1038 beego.RouterHandler("/chat/:info(.*)", sockjshandler)
...@@ -1013,7 +1086,9 @@ sockjshandler摰鈭`http.Handler` ...@@ -1013,7 +1086,9 @@ sockjshandler摰鈭`http.Handler`
1013 1086
1014 通过上面的代码很简单的实现了一个多人的聊天室。上面这个只是一个sockjs的例子,我想通过大家自定义`http.Handler`,可以有很多种方式来进行扩展beego应用。 1087 通过上面的代码很简单的实现了一个多人的聊天室。上面这个只是一个sockjs的例子,我想通过大家自定义`http.Handler`,可以有很多种方式来进行扩展beego应用。
1015 1088
1089
1016 ## 部署编译应用 1090 ## 部署编译应用
1091
1017 Go语言的应用最后编译之后是一个二进制文件,你只需要copy这个应用到服务器上,运行起来就行。beego由于带有几个静态文件、配置文件、模板文件三个目录,所以用户部署的时候需要同时copy这三个目录到相应的部署应用之下,下面以我实际的应用部署为例: 1092 Go语言的应用最后编译之后是一个二进制文件,你只需要copy这个应用到服务器上,运行起来就行。beego由于带有几个静态文件、配置文件、模板文件三个目录,所以用户部署的时候需要同时copy这三个目录到相应的部署应用之下,下面以我实际的应用部署为例:
1018 1093
1019 $ mkdir /opt/app/beepkg 1094 $ mkdir /opt/app/beepkg
......
...@@ -34,6 +34,7 @@ beego是一个类似tornado的Go应用框架,采用了RESTFul的方式来实 ...@@ -34,6 +34,7 @@ beego是一个类似tornado的Go应用框架,采用了RESTFul的方式来实
34 beego.Run() 34 beego.Run()
35 } 35 }
36 36
37
37 # beego 指南 38 # beego 指南
38 39
39 * [为什么设计beego](Why.md) 40 * [为什么设计beego](Why.md)
...@@ -43,6 +44,7 @@ beego是一个类似tornado的Go应用框架,采用了RESTFul的方式来实 ...@@ -43,6 +44,7 @@ beego是一个类似tornado的Go应用框架,采用了RESTFul的方式来实
43 * [beego案例](Application.md) 44 * [beego案例](Application.md)
44 * [热升级](HotUpdate.md) 45 * [热升级](HotUpdate.md)
45 46
47
46 # API接口 48 # API接口
47 49
48 API对于我们平时开发应用非常有用,用于查询一些开发的函数,godoc做的非常好了 50 API对于我们平时开发应用非常有用,用于查询一些开发的函数,godoc做的非常好了
......
1 # 一步一步跟我写博客 1 # 一步一步跟我写博客
2 2
3
3 ## 创建项目 4 ## 创建项目
4 5
6
5 ## 数据库结构设计 7 ## 数据库结构设计
6 8
9
7 ## 控制器设计 10 ## 控制器设计
8 11
12
9 ## 模板设计 13 ## 模板设计
10 14
15
11 ## 用户登陆退出 16 ## 用户登陆退出
12 17
18
13 ## 数据库操作 19 ## 数据库操作
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!