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)
Open address [http://127.0.0.1:8080](http://127.0.0.1:8080) in your browser and you will see "hello world".
What happened in behind above example?
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.
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.
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`.
4. Define main function. All applications in Go use main function as entry point as C does.
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.
6. Run application in port 8080 as default, press `Ctrl+c` to exit.
## New project
Get into your $GOPATH, then use following command to setup Beego project:
bee create hello
It generates folders and files for your project, directory structure as follows:
.
├── conf
│ └── app.conf
├── controllers
│ └── default.go
├── main.go
├── models
├── static
│ ├── css
│ ├── img
│ └── js
└── views
└── index.tpl
## Development mode
Beego uses development mode as default, you can use following code to change mode in your application:
beego.RunMode = "pro"
Or use configuration file in `conf/app.conf`, and input following content:
runmode = pro
No differences between two ways.
In development mode, you have following effects:
- If you don't have directory `views`, it prints following error prompt:
2013/04/13 19:36:17 [W] [stat views: no such file or directory]
- It doesn't cache template and reload every time.
- If panic occurs in your server, it prints information like following screen shot:
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:
`beego.Controller` implemented all of them, so you just use this struct as anonymous field in your controller struct. Of course you have to overload corresponding methods for more specific usages.
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`.
This method executes when client sends request as GET method, 403 as default status code. Users overload this method for customized handle process of GET method.
This method executes when client sends request as POST method, 403 as default status code. Users overload this method for customized handle process of POST method.
This method executes when client sends request as DELETE method, 403 as default status code. Users overload this method for customized handle process of DELETE method.
This method executes when client sends request as PUT method, 403 as default status code. Users overload this method for customized handle process of PUT method.
This method executes when client sends request as HEAD method, 403 as default status code. Users overload this method for customized handle process of HEAD method.
This method executes when client sends request as PATCH method, 403 as default status code. Users overload this method for customized handle process of PATCH method.
This method executes when client sends request as OPTIONS method, 403 as default status code. Users overload this method for customized handle process of OPTIONS method.
This method executes after corresponding method finished, empty as default. User overload this method for more usages like close database, clean data, etc.
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:
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.
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:
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)。
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:
Beego supports two kinds of extensions for template files, which are `tpl` and `html`, if you want to use other extensions, you have to use following code to let Beego know:
If you enabled auto-render and you don't tell Beego which template file you are going to use in controller methods, Beego uses following format to find the template file if it exists:
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`.
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.
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:
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)
###File upload
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.
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.
This function is mainly used to read file name element `the_file` in form and returns corresponding information. You can use this information either filter or save files.
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:
You can also throw an exception in your controller as follows:
func (this *MainController) Get() {
this.Abort("401")
v := this.GetSession("asta")
if v == nil {
this.SetSession("asta", int(1))
this.Data["Email"] = 0
} else {
this.SetSession("asta", v.(int)+1)
this.Data["Email"] = v.(int)
}
this.TplNames = "index.tpl"
}
Then Beego will not execute rest code of the function body when you call `this.Abort("401")`, and gives following default page view to users:
![](images/401.png)
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:
func page_not_found(rw http.ResponseWriter, r *http.Request){
You may be able to use your own `404.html` for your 404 error.
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:
func dbError(rw http.ResponseWriter, r *http.Request){
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.
Setting save path or link address of corresponding file, MySQL and redis engines, default is empty, corresponding arguments in configuration file: sessionsavepath
To use cache, you need to initialize a `beego.NewBeeCache` object and set expired time, and enable expired check. Then you can use following methods to achieve other operations:
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.
Your project may have a lot of log outputs, but you don't want to output everything after your application is running on the internet, for example, you want to ignore Trace, Debug and Info level log outputs, you can use following setting:
This value indicates whether enable pprof or not, default is false, and you can use following address to see goroutine execution status once you enable this feature.
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.