da1fe2fe by astaxie

modify readme

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