2ad44786 by astaxie

Merge pull request #40 from Unknwon/master

English version of readme.md and purposes.md
2 parents 140b513c 40675d93
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
24 go get github.com/astaxie/beego 25 package main
25 26
26 ## Quick Start 27 import (
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" 28 "github.com/astaxie/beego"
34 ) 29 )
35 30
36 type MainController struct { 31 type MainController struct {
37 beego.Controller 32 beego.Controller
38 } 33 }
39 34
40 func (this *MainController) Get() { 35 func (this *MainController) Get() {
41 this.Ctx.WriteString("hello world") 36 this.Ctx.WriteString("hello world")
42 } 37 }
43 38
44 func main() { 39 func main() {
45 beego.Router("/", &MainController{}) 40 beego.Router("/", &MainController{})
46 //beego.HttpPort = 8080 // default
47 beego.Run() 41 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
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.
149
150 - Patch()
151
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.
153
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 } 42 }
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
249 ### template function
250 beego support users to define template function like this:
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 }
402 lg := log.New(fd, "", log.Ldate|log.Ltime)
403 beego.SetLogger(lg)
404
405
406 ### Supported log levels
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.
408 - Debug - For detailed system behavior reports and diagnostic messages to help to locate problems during development.
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'.
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](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
......
1 # Design purposes and ideas
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
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
6 I used to use CI in PHP and tornado in Python, there are both lightweight, so they has following advantages:
7
8 1. Save time for handling general problems, I only need to care about logic part.
9 2. Learn more 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
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
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
16 The controller is the most important part of whole MVC model, and Beego uses the interface and ideas I said above for the controller. Although I haven't decided to have to design the model part, everyone is welcome to implement data management by referencing Beedb, my another open source project. I simply adopt Go built-in template engine for the view part, but add more commonly used functions as template functions. This is how a simple web framework looks like, but I'll keep working on form processing, session handling, log recording, configuration, automated operation, etc, to build a simple but complete web framework.
17
18 - [Introduction](README.md)
19 - [Installation](Install.md)
...\ 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!