d6cd1322 by astaxie

go on write docs

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