Merge pull request #444 from DeepAnchor/master

English grammar and translation fixes - 13.0.md to 14.7.md
This commit is contained in:
astaxie
2015-04-01 23:55:58 +08:00
18 changed files with 235 additions and 231 deletions

View File

@@ -115,7 +115,7 @@ We introduced a simple session manager's working principles in the previous sect
}
The above example implemented a memory based session storage mechanism. It uses its `init()` function to register this storage engine to the session manager. So how do we register this engine from our main program?
The above example implements a memory based session storage mechanism. It uses its `init()` function to register this storage engine to the session manager. So how do we register this engine from our main program?
import (
"github.com/astaxie/session"

View File

@@ -1,6 +1,6 @@
# 11.1 Error handling
Go's major design considerations are rooted in the following ideas: a simple, clear, and concise syntax (similar to C), statements are explicit and don't contain hidden any hidden or unexpected things. Go's error handling scheme reflects all of these principles in the way that it's implemented. If you're familiar with the C language, you'll know that it's common to return -1 or NULL values to indicate that an error has occurred. However users who are not familiar with C's API will not know exactly what these return values mean. In C, it's not explicit whether a value of `0` indicates success of failure. On the other hand, Go explicitly defines a type called `error` for the sole purpose of expressing errors. Whenever a function returns, we check to see whether the error variable is `nil` or not to determine if the operation was successful. For example, the `os.Open` function fails, it will return a non-nil error variable.
Go's major design considerations are rooted in the following ideas: a simple, clear, and concise syntax (similar to C) and statements which are explicit and don't contain any hidden or unexpected things. Go's error handling scheme reflects all of these principles in the way that it's implemented. If you're familiar with the C language, you'll know that it's common to return -1 or NULL values to indicate that an error has occurred. However users who are not familiar with C's API will not know exactly what these return values mean. In C, it's not explicit whether a value of `0` indicates success of failure. On the other hand, Go explicitly defines a type called `error` for the sole purpose of expressing errors. Whenever a function returns, we check to see whether the error variable is `nil` or not to determine if the operation was successful. For example, the `os.Open` function fails, it will return a non-nil error variable.
func Open(name string) (file * File, err error)
@@ -21,11 +21,7 @@ Similar to the `os.Open` function, the functions in Go's standard packages all r
Error() string
}
`error` is a built-in interface type, we can / builtin / pack below to find the appropriate definition. And we have a lot of internal error is used inside the package packet errors following implementation structure errorString private
`error` is a built-in interface type. We can find the corresponding definition in the builtin package below. We also have a lot of internal packages using the error in a private structure called `errorString`, which implements the error interface:
`error` is a built-in interface type. We can find its definition in the builtin package below. We also have a lot of internal packages which use `error` in a private structure called `errorString`, which implements the error interface:
// errorString is a trivial implementation of error.
type errorString struct {

View File

@@ -1,8 +1,8 @@
# 13 Build a web framework
# 13 Building a web framework
Preceding twelve chapter describes how to develop Web applications through Go, introduced a lot of basic knowledge, development tools and techniques, then we pass this knowledge in this chapter to implement a simple Web framework. Go language to achieve through a complete frame design, the main contents of this framework, the first section describes the structure of a Web framework planning, such as using the MVC pattern to develop, program execution process design, etc.; second section describes the framework the first feature: Routing, how to get access to the URL mapped to the corresponding processing logic; third section describes the processing logic, how to design a common controller, object inheritance after the handler how to handle response and request; fourth section describes how to framework some auxiliary functions, such as log processing, configuration information, etc.; fifth section describes how to implement a blog-based Web framework, including Bowen published, modify, delete, display a list of other operations.
The Preceding twelve chapters describe how to develop web applications in Go, introducing a lot of basic knowledge, development tools and techniques. In this chapter, we will be using this knowledge to implement a simple web framework. The first section of this chapter will take you through the planning and design stage of building a web framework. We'll look at leveraging the MVC pattern as well as designing program execution flow, among other things. The second section will describe the first feature of our framework: Routing; namely, how to map URLs to processing logic. Then in the third section, we describe the processing logic itself, which involves designing generic controllers, and how to handle requests and return responses after inheriting from an object handler. Next, we describe some of the auxiliary functionality common to most web frameworks, such as log processing, information configuration, etc. Finally, we'll implement a simple blogging system on top of our framework which will demonstrate the application logic necessary for publishing, modifying, deleting, and displaying lists of blog posts.
Through such a complete project example, I expect to be able to allow readers to understand how to develop Web applications, how to build your own directory structure, how to achieve routing, how to achieve the MVC pattern and other aspects of developing content. In the framework prevalent today, MVC is no longer a myth. Many programmers often heard discussions which frame is good, which frame is not good, in fact, the framework is only a tool, there is no good or bad, only suitable or unsuitable, for his is the best, so we write their own framework for the church, then different needs can use their own ideas to be realized.
By seeing first-hand how to implement such a complete project from scratch, you will hopefully have a better understanding of the inner workings of Go web applications. You'll be comfortable building your own project directory structures, implementing URL routers and utilizing MVC, among other aspects of web development. Among the frameworks prevalent today, MVC is no longer a myth. It's not uncommon to hear programmers arguing about which frameworks are good and which are bad, which is often too shallow of an approach. Frameworks are only tools, and some tools are more suitable for certain applications than others. There are no universally good or bad tools. Thus, by teaching yourself how to write a framework from scratch, you will be able to tailor-make the perfect tool to best realize your ideas!
## Links

View File

@@ -1,43 +1,43 @@
# 13.1 Project program
# 13.1 Project planning
Need to do anything good plan, then we in the development blog system, also need to do the planning, how to set up the directory structure, how to understand the flow of the project, when we understand the execution of the application process, then the next the design becomes relatively easy to code
Anything you intend to do well must first be planned well. In our case, our intention is to develop a blogging system, so the first step we should take is to design the flow of the application in its entirety. When we have a clear understanding of the our application's process of execution, the subsequent design and coding steps become much easier.
## GOPATH and project settings
Assuming that the file system specified GOPATH ordinary directory name, of course, we can easily set up a directory name, then its path into GOPATH. GOPATH described earlier can be multiple directories: set the environment variable in the window system ; in linux/MacOS system as long as the input terminal command `export gopath =/home/astaxie/gopath`, but must ensure that GOPATH the code below three directories pkg directory, bin, src. New Project source code in src directory, now tentatively our blog directory called beeblog, the following is in the window environment variables and directory structure screenshot:
Let's proceed by assuming that our GOPATH points to a folder with with an ordinary directory name (if not, we can easily set up a suitable directory and set its path as the GOPATH). As we've describe earlier, a GOPATH can contain more than one directory: in Windows, we can set this as an environment variable; in linux/OSX systems, GOPATH can be set using `export`, i.e: `export gopath=/path/to/your/directory`, as long as the directory which GOPATH points to contains the three sub-directories: `pkg`, `bin` and `src`. Below, we've placed the source code of our new project in the `src` directory with the tentative name `beelog`. Here are some screenshots of the Windows environment variables as well as of the directory structure.
![](images/13.1.gopath.png?raw=true)
Figure 13.1 GOPATH setting environment variables
Figure 13.1 Setting the GOPATH environment variable
![](images/13.1.gopath2.png?raw=true)
Figure 13.2 working directory in $ gopath/src under
Figure 13.2 The working directory under $gopath/src
## Application flowchart
Blog system is based on the model - view - controller of this design pattern. MVC is a logic of the application layer and the presentation layer separation is structured. In practice, due to the presentation layer separate from the Go out, so it allows your page includes only a small script.
Our blogging system will be based on the model-view-controller design pattern. MVC is the separation of the application logic from the presentation layer. In practice, when we keep the presentation layer separated, we can drastically reduce the amount of code needed on our web pages.
- Models(Model) represents the data structure. Generally speaking, the model class will contain remove, insert, update database information, etc. These functions.
- View(View) is displayed to the user's information structure and style. A view is usually a web page, but in Go, a view can also be a page fragment, such as page header, footer. It can also be an RSS page, or any other type of " page ", Go template package has been implemented to achieve a good part of the View layer of functionality.
- Controller(Controller) is a model, view, and anything else necessary for processing the HTTP request intermediary between resources and generate web pages.
- Models represent data as well as the rules and logic governing it. In General, a model class will contain functions for removing, inserting and updating database information.
- Views are a representation of the state of a model. A view is usually a page, but in Go, a view can also be a fragment of a page, such as a header or footer. It can also be an RSS feed, or any other type of "page". Go's `template` package provides very good support for view layer functionality.
- Controllers are the glue logic between the model and view layers and encompasses all the intermediary logic necessary for handling HTTP requests and generating Web pages.
The following figure shows the framework of the project design is how the data flow throughout the system:
The following figure is an overview of the project framework and demonstrates how data will flow through the system:
![](images/13.1.flow.png?raw=true)
Figure 13.3 the frame data stream
Figure 13.3 framework data flow
1. Main.go as an application portal, running blog initialize some basic resources needed, configuration information, listen port.
2. Check the HTTP request routing function, based on the URL and method to determine who( control layer ) to process the request forwarding resources.
3. If the cache file exists, it will bypass the normal process execution, is sent directly to the browser.
4. Safety Testing: The application before the call controller, HTTP requests, and any user submitted data will be filtered.
5. controller loading model, core libraries, auxiliary functions, as well as any treatment other resources required for a particular request, the controller is primarily responsible for handling business logic.
6. Output view layer rendering good to be sent to the Web browser content. If on the cache, the cache is first view, the routine for future requests.
1. Main.go is the application's entry point and initializes some basic resources required to run the blog such as configuration information, listening ports, etc.
2. Routing checks all incoming HTTP requests and, according to the method, URL and parameters, matches it with the corresponding controller action.
3. If the requested resource has already been cached, the application will bypass the usual execution process and return a response directly to the user's browser.
4. Security detection: The application will filter incoming HTTP requests and any other user submitted data before handing it off to the controller.
5. Controller loads models, core libraries, and any other resources required to process specific requests. The controller is primarily responsible for handling business logic.
6. Output the rendered view to be sent to the client's web browser. If caching has been enabled, the first view is cached for future requests to the same resource.
## Directory structure
According to the above application process design, blog design the directory structure is as follows:
According to the framework flow we've designed above, our blog project's directory structure should look something like the following:
|——main.go import documents
|——conf configuration files and processing module
@@ -47,16 +47,16 @@ According to the above application process design, blog design the directory str
|——static static file directory
|——views view gallery
## Frame design
## Framework design
In order to achieve a quick blog to build, based on the above process design intends to develop a minimization framework, which includes routing capabilities, support for REST controllers, automated template rendering, log system, configuration management, and so on.
In order to quickly build our blog, we need to develop a minimal framework based on the application we've designed above. The framework should include routing capabilities, support for RESTful controllers, automated template rendering, a logging system, configuration management, and more.
## Summary
This section describes the blog system to the directory from the setup GOPATH establish such basic information, but also a brief introduction of the framework structure using the MVC pattern, blog system data flow execution flow, and finally through these processes designed blog system directory structure, thus we basically completed a framework to build the next few sections we will achieve individually.
This section describes the initial design of our blogging system, from setting up our GOPATH to briefly introducing the MVC pattern. We also looked at the flow of data and the execution sequence of our blogging system. Finally, we designed the structure of our project directory. At this point, we've basically completed the groundwork required for assembling our framework. In the next few sections, we will implement each of the components we've discussed, one by one.
## Links
- [Directory](preface.md)
- Previous section: [Build a web framework](13.0.md)
- Next section: [Customized routers](13.2.md)
- Previous section: [Building a web framework](13.0.md)
- Next section: [Customizing routers](13.2.md)

View File

@@ -1,17 +1,17 @@
# 13.2 Customized routers
# 13.2 Customizing routers
## HTTP routing
HTTP HTTP request routing components corresponding function handed process( or a struct method ), as described in the previous section structure, in the frame corresponds to a routing event handler, and the event comprises:
The HTTP routing component is responsible for mapping HTTP requests to a corresponding function or `struct` method. The router takes two key pieces of information from incoming requests:
- User requests a path(path)( e.g.:/user/123,/article/123), of course, the query string information(e.g., ? Id = 11)
- HTTP request method(method)(GET, POST, PUT, DELETE, PATCH, etc. )
-The user requested path (for example, `/user/123,/article/123`), and any query strings or parameters that come with it (for example, `?id=11`)
-The HTTP request method (GET, POST, PUT, and DELETE, PATCH, etc.)
The router is based on the user's request is forwarded to the respective event information processing function( control layer ).
The router then forwards the request to the handler function (controller layer) that has been registered with that particular HTTP method and path.
## Default route to achieve
## Default routing implementation
Have been introduced in section 3.4 Go's http package Detailed, which introduced the Go's http package how to design and implement routing, here continue to be an example to illustrate:
In section 3.4, we introduced Go's `http` package in detail, which included how to design and implement routing. Here, we take another look at an example that illustrates the routing process:
func fooHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
@@ -25,14 +25,14 @@ Have been introduced in section 3.4 Go's http package Detailed, which introduced
log.Fatal(http.ListenAndServe(":8080", nil))
The above example calls the http default DefaultServeMux to add a route, you need to provide two parameters, the first parameter is the resource you want users to access the URL path( stored in r.URL.Path), the second argument is about to be executed function to provide the user access to resources. Routing focused mainly on two ideas:
The example above calls `http`'s default mux called `DefaultServeMux`, implicitly specified by the `nil` parameter in the call to `http.ListenAndServe`. The `http.Handle` function takes two parameters: the first parameter is the resource you want users to access, specified by its URL path (which is stored in `r.URL.Path`) and the second argument binds a handler function with this path. The Router has two main jobs:
- Add routing information
- According to the user request is forwarded to the function to be performed
- To add and store routing information
- To forward requests to a handler function for processing
Go add default route is through a function `http.Handle` and `http.HandleFunc`, etc. to add, the bottom is called `DefaultServeMux.Handle(pattern string, handler Handler)`, this function will set the routing information is stored in a map information in `map [string] muxEntry`, which would address the above said first point.
By default, Go routes are handled with `http.Handle` and `http.HandleFunc` types, registered by default through the underlying `DefaultServeMux.Handle(pattern string, handler Handler)` function. This function maps resource paths to handlers and stores them in a `map[string]muxEntry` map. This is the first job that we mentioned above.
Go listening port, and then receives the tcp connection thrown Handler to process, the above example is the default nil `http.DefaultServeMux`, `DefaultServeMux.ServeHTTP` by the scheduling function, the previously stored map traverse route information, and the user URL accessed matching to check the corresponding registered handler, so to achieve the above mentioned second point.
When the application is running, the Go server listens to a port. When it receives a tcp connection, it uses a `Handler` to process it. As aforementioned, since the `Handler` in the example above is `nil`, the default router `http.DefaultServeMux` is used. Using the map of previously stored routes, `DefaultServeMux.ServeHTTP` will dispatch the request to the first handler with a matching path. This is the router's second job.
for k, v := range mux.m {
if !pathMatch(k, path) {
@@ -44,21 +44,21 @@ Go listening port, and then receives the tcp connection thrown Handler to proces
}
}
## Beego routing framework to achieve
## Routing with Beego
Almost all Web applications are based routing to achieve http default router, but the router comes Go has several limitations:
At present, most Go web applications base their routing on `http`'s default router, however this has several limitations:
- Does not support parameter setting, such as/user/: uid This pan type matching
- Not very good support for REST mode, you can not restrict access methods, such as the above example, user access/foo, you can use GET, POST, DELETE, HEAD, etc. Access
- General site routing rules too much, write cumbersome. I'm in front of an API to develop their own applications, routing rules have thirty several, in fact, this route after more than can be further simplified by a simplified method of the struct
- Does not support dynamic routes with parameters, such as `the/user/:UID`
- Does not have good support for REST. The access methods cannot be restricted; for instance in the above example, when users access `/foo`, they can use the GET, POST, DELETE, and HEAD HTTP methods, among others.
- In large apps, routing rules can become repetitive and cumbersome. Personally, I've developed simple web APIs composed of nearly thirty routing rules when in fact, these rules could have been further simplified using method structs.
beego framework routers based on the above few limitations to consider the design of a REST approach to achieve routing, routing design is based on two points above the default design Go to consider: store -and-forward routing routing
The Beego framework's router is designed to overcome these limitations, taking the REST paradigm into consideration and simplifying the storing and forwarding of routes and requests.
### Storing a routing
### Storing routes
For the previously mentioned restriction point, we must first solve the arguments supporting the need to use regular, second and third point we passed a viable alternative to solve, REST method corresponds to a struct method to go, and then routed to the struct instead of a function, so that when the forward routing method can be performed according to different methods.
To address the first limitation of the default router, we need to be able to support dynamic URL parameters. For the second and third points, we adopt an alternative approach,mapping REST methods to struct methods and routing requests to this struct instead handler functions. This way, a forwarded request can be handled according to their HTTP method.
Based on the above ideas, we designed two data types controllerInfo( save path and the corresponding struct, here is a reflect.Type type ) and ControllerRegistor(routers are used to save user to add a slice of routing information, and the application of the framework beego information )
Based on the above ideas, we've designed two data types: `controllerInfo`, which saves the path and the corresponding `controllerType` struct as a `reflect.Type` type, and `ControllerRegistor`, which saves routing information for the specified Beego application.
type controllerInfo struct {
regex *regexp.Regexp
@@ -71,11 +71,11 @@ Based on the above ideas, we designed two data types controllerInfo( save path a
Application *App
}
ControllerRegistor external interface function has
ControllerRegistor's external interface contains the following method:
func(p *ControllerRegistor) Add(pattern string, c ControllerInterface)
Detailed implementation is as follows:
Its detailed implementation is as follows:
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
parts := strings.Split(pattern, "/")
@@ -86,7 +86,7 @@ Detailed implementation is as follows:
if strings.HasPrefix(part, ":") {
expr := "([^/]+)"
//a user may choose to override the defult expression
//a user may choose to override the default expression
// similar to expressjs: /user/:id([0-9]+)
if index := strings.Index(part, "("); index != -1 {
@@ -100,7 +100,7 @@ Detailed implementation is as follows:
}
//recreate the url pattern, with parameters replaced
//by regular expressions. then compile the regex
//by regular expressions. Then compile the regex.
pattern = strings.Join(parts, "/")
regex, regexErr := regexp.Compile(pattern)
@@ -124,20 +124,20 @@ Detailed implementation is as follows:
### Static routing
Above we achieve the realization of dynamic routing, Go the http package supported by default static file handler FileServer, because we have implemented a custom router, then the static files also need to set their own, beego static folder path stored in the global variable StaticDir, StaticDir is a map type to achieve the following:
We've implemented dynamic routing in our example above. By default, Go's `http` package supports serving static files with `http.FileServer`, which return a `Handler`. Since we have implemented a custom router, we will also need a way of handling static files. Beego's static folder path is saved in a global variable called `StaticDir`, which maps URL to corresponding paths. The `SetStaticPath`'s implementation can be seen below:
func (app *App) SetStaticPath(url string, path string) *App {
StaticDir[url] = path
return app
}
Applications can use the static route is set to achieve the following manner:
The application's static routes can be set like so:
beego.SetStaticPath("/img", "/static/img")
### Forwarding route
### Forwarding routes
Forwarding route in the routing is based ControllerRegistor forwarding information, detailed achieve the following code shows:
We can forward routes based on the forwarding information contained within `ControllerRegistor`. The detailed implementation can be seen in the following code snippet:
// AutoRoute
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@@ -249,22 +249,22 @@ Forwarding route in the routing is based ControllerRegistor forwarding informati
### Getting started
After the design is based on the routing can solve the previously mentioned three restriction point, using a method as follows:
Using our router design, we can solve the three limitations mentioned earlier. The three main use-cases are:
The basic use of a registered route:
Registering route handlers:
beego.BeeApp.RegisterController("/", &controllers.MainController{})
Parameter registration:
Handling dynamic parameters:
beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
Are then matched:
Regex matching:
beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
## Links
- [Directory](preface.md)
- Previous section: [Project program](13.1.md)
- Next section: [Design controllers](13.3.md)
- Previous section: [Project planning](13.1.md)
- Next section: [Designing controllers](13.3.md)

View File

@@ -1,14 +1,14 @@
# 13.3 Design controllers
# 13.3 Designing controllers
Most of the traditional MVC framework is based on the design of postfix Action mapping, however, is now popular REST-style Web architecture. Although the use of Filter or rewrite URL rewriting can be achieved through a REST-style URL, but why not just design a new REST-style MVC framework it ? This section is based on this idea on how to start from scratch to design a REST-style MVC framework based on the controller, to maximize simplify Web application development, or even write a single line of code to achieve the "Hello, world".
Most traditional MVC frameworks are based on suffix action mapping. Nowadays, the REST style web architecture is becoming increasingly popular. One can implement REST-style URLs by filtering or rewriting them, but why not just design a new REST-style MVC framework instead? This section is based on this idea, and focusses on designing and implementing a controller based, REST-style MVC framework from scratch. Our goal is to simplify the development of web applications, perhaps even allowing us to write a single line of code capable of serving "Hello, world".
## Controller role
## The controller's role
MVC design pattern is the most common Web application development framework model, by separating Model( model ), View( view ) and the Controller( controller ) can be more easily achieved easily extensible user interface(UI). Model refers to the background data returned ; View refers to the need to render the page, usually a template page, the content is usually rendered HTML; Controller refers to Web developers to write controllers handle different URL, such as the route described in the previous section is a URL request forwarded to the process controller, controller in the whole MVC framework plays a central role, responsible for handling business logic, so the controller is an essential part of the whole framework, Model and View for some business needs can not write, for example, no data processing logic processing, no page output 302 and the like do not need to adjust the Model and View, but the controller of this part is essential.
The MVC design pattern is currently the most used framework model for web applications. By keeping Models, Views and Controllers separated, we can keep our web applications modular, maintainable, testable and extensible. A model encapsulates data and any of the business logic that governs that data, such as accessibility rules, persistence, validation, etc. Views serve as the data's representation and in the case of web applications, they usually live as templates which are then rendered into HTML and served. Controllers serve as the "glue" logic between Models and Views and typically have methods for handling different URLs. As described in the previous section, when a URL request is forwarded to a controller by the router, the controller delegates commands to the Model to perform some action, then notifies the View of any changes. In certain cases, there is no need for models to perform any kind of logical or data processing, or for any views to be rendered. For instance, in the case of an HTTP 302 redirect, no view needs to be rendered and no processing needs to be performed by the Model, however the Controller's job is still essential.
## Beego the REST design
## RESTful design in Beego
Previous section describes the routing function to achieve a registered struct, and the struct implements REST approach, so we need to design a controller for logic processing base class, where the main design of the two types, a struct, an interface
The previous section describes registering route handlers with RESTful structs. Now, we need to design the base class for a logic controller that will be composed of two parts: a struct and interface type.
type Controller struct {
Ct *Context
@@ -34,7 +34,7 @@ Previous section describes the routing function to achieve a registered struct,
Render() error //method executed after the corresponding method to render the page
}
Then add function described earlier, when a route is defined ControllerInterface type, so long as we can implement this interface, so our base class Controller to achieve the following methods:
Then add the route handling function described earlier in this chapter. When a route is defined to be a `ControllerInterface` type, so long as we can implement this interface, we can have access to the following methods of our base class controller.
func (c *Controller) Init(ct *Context, cn string) {
c.Data = make(map[interface{}]interface{})
@@ -115,18 +115,17 @@ Then add function described earlier, when a route is defined ControllerInterface
c.Ct.Redirect(code, url)
}
Above, the controller base class already implements the functions defined in the interface. Through our routing rules, the request will be routed to the appropriate controller which will in turn execute the following methods:
At the controller base class already implements the interface defined functions performed by routing the appropriate controller according url principles will be followed by implementation of the following:
Init() initializes
Prepare() before the execution of the initialization, each subclass can inherit to implement the function
method() depending on the method to perform different functions: GET, POST, PUT, HEAD, etc. sub-classes to implement these functions, if not achieved, then the default is 403
Render() optional, according to a global variable to determine whether to execute AutoRender
Finish() after the implementation of the action, each subclass inherits the function can be achieved
Init() initialization routine
Prepare() pre-initialization routine; each inheritting subclass may implement this function
method() depending on the request method, perform different functions: GET, POST, PUT, HEAD, etc. Subclasses should implement these functions; if not implemented, then the default is 403
Render() optional method. Determine whether or not to execute according to the global variable "AutoRender"
Finish() is executed after the action been completed. Each inheritting subclass may implement this function
## Application guide
Above beego Framework base class to complete the design of the controller, then we in our application can be to design our approach:
Above, we've just finished discussing Beego's implementation of the base controller class. We can now use this information to design our request handling, inheriting from the base class and implementing the necessary methods in our own controller.
package controllers
@@ -144,11 +143,11 @@ Above beego Framework base class to complete the design of the controller, then
this.TplNames = "index.tpl"
}
The way we achieved above subclass MainController, implements Get method, so if the user through other means(POST/HEAD, etc. ) to access the resource will return 403, and if it is Get access, because we set the AutoRender = true, then play in the implementation of the Get method is performed automatically after the Render function, it will display the following interface:
In the code above, we've implemented a subclass of `Controller` called `MainController` which only implements the `Get()` method. If a user tries to access the resource using any of the other HTTP methods (POST, HEAD, etc), a 403 Forbidden will be returned. However, if a user submits a GET request to the resource and we have have the `AutoRender` variable set to `true`, the resource's controller will automatically call its `Render()` function, rendering the corresponding template and responding with the following:
![](images/13.4.beego.png?raw=true)
index.tpl code is shown below, we can see the data set and display are quite simple:
The `index.tpl` code can be seen below; as you can see, parsing model data into a template is quite simple:
<!DOCTYPE html>
<html>
@@ -164,5 +163,5 @@ index.tpl code is shown below, we can see the data set and display are quite sim
## Links
- [Directory](preface.md)
- Previous section: [Customized routers](13.2.md)
- Previous section: [Customizing routers](13.2.md)
- Next section: [Logs and configurations](13.4.md)

View File

@@ -1,17 +1,16 @@
# 13.4 Logs and configurations
# 13.4 Logging and configuration
## The importance of logs and configuration
## The importance of logging and configuration
It has been introduced in the log in our program development plays a very important role, through the debug log we can record our information, had introduced a logging system seelog, depending on the different log level output of this program for program development and deployment is crucial. We can set the level in program development low point, when the level is set to deploy high, so we developed the debugging information can be masked.
Previously in the book, we saw that event logging plays a very important role in application development. With adequate logging, we can record crucial information that can later be dissected for debugging and optimization purposes. In the section where we looked at the seelog logging utility, we saw that it had settings for various log level gradations, which can be essential for program development and deployment; we can set the logging level lower in a development environment, while setting it high in production so that we can mask extraneous information when we are trying to debug our application.
Configuration module for application deployment involves a number of different server configuration information is very useful, for example, some database configuration information, monitor port, listen address, etc. can all be configured via the configuration file, so that our application will have great flexibility, the configuration file can be configured to be deployed in different machines, you can connect different databases and the like.
Setting up server configuration module for deploying an application involves a number of different server settings. For example, we typically need to provide information regarding database configuration, listening ports, etc., via the configuration file. Setting up a centralized configuration file allows us the flexibility of deploying on different machines and connecting to remote databases, if needed.
## Beego log design
## The Beego logging system
beego deployment log design ideas from seelog, depending on the level for logging, but beego relatively lightweight logging system design, the use of the system log.Logger interfaces, the default output to os.Stdout, users can implement this interface then through beego.SetLogger set custom output, detailed implementation is as follows:
The Beego logger's design borrows ideas from seelog provides similar functionality in terms of setting logging levels. Beego's system is, however, more lightweight and makes use of the Go's `log.Logger` interface. By default, logs are outputted to os.Stdout, but users can implement this interface through `beego.SetLogger` to customize this. A detailed example of an implemented interface can be seen below:
// Log levels to control the logging output.
// Log levels for controlling the logging output.
const (
LevelTrace = iota
LevelDebug
@@ -25,7 +24,7 @@ beego deployment log design ideas from seelog, depending on the level for loggin
var level = LevelTrace
// LogLevel returns the global log level and can be used in
// own implementations of the logger interface.
// a custom implementations of the logger interface.
func Level() int {
return level
}
@@ -36,7 +35,7 @@ beego deployment log design ideas from seelog, depending on the level for loggin
level = l
}
This section implements the above log log grading system, the default level is the Trace, users can set different grading SetLevel.
This section implements the above log grading system. The default level is set to Trace and users can customize grading levels using `SetLevel`.
// logger references the used application logger.
var BeeLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
@@ -88,38 +87,38 @@ This section implements the above log log grading system, the default level is t
}
}
Above this piece of code initializes a BeeLogger default object, the default output to os.Stdout, users can achieve a logger beego.SetLogger to set the interface output. Which are to achieve the six functions:
The code snippet above initializes a `BeeLogger` object by default, outputting logs to `os.Stdout`. As mentioned, users can implement `beego.SetLogger` to customize the logger's output. `BeeLogger` implements six functions:
- Trace( general record information, for example as follows:)
- Trace (record general information, for example:)
- "Entered parse function validation block"
- "Validation: entered second 'if'"
- "Dictionary 'Dict' is empty. Using default value"
- Debug( debug information, for example as follows:)
- Debug (debugging information, for example:)
- "Web page requested: http://somesite.com Params = '...'"
- "Response generated. Response size: 10000. Sending."
- "New file received. Type: PNG Size: 20000"
- Info( print information, for example as follows:)
- Info (printing general information, for example:)
- "Web server restarted"
- "Hourly statistics: Requested pages: 12345 Errors: 123..."
- "Service paused. Waiting for 'resume' call"
- Warn( warning messages, for example as follows:)
- Warn (warning messages, for example:)
- "Cache corrupted for file = 'test.file'. Reading from back-end"
- "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
- "No response from statistics server. Statistics not sent"
- Error( error messages, for example as follows:)
- Error (error messages, for example:)
- "Internal error. Cannot process request# 12345 Error:...."
- "Cannot perform login: credentials DB not responding"
- Critical( fatal error, for example as follows:)
- Critical (fatal errors, for example:)
- "Critical panic received:.... Shutting down"
- "Fatal error:... App is shutting down to prevent data corruption or loss"
Each function can be seen on the level of judgment which has, so if we set at deployment time level = LevelWarning, then Trace, Debug, Info will not have any of these three functions output, and so on.
You can see that each of these levels has a specific purpose. For instance if we set the logging level to Warn (`level=LevelWarning`), at the time of deployment, all of the lower level logs (Trace, Debug, Info) will not output anything.
## Beego configuration design
Configuration information parsing, beego implements a key = value configuration file read, similar ini configuration file format is a file parsing process, and then parse the data saved to the map, the last time the call through several string, int sort of function call returns the corresponding value, see the following specific implementation:
For processing configuration information, Beego implements a key=value file parser which reads information formatted similarly to `ini` configuration files. The parser reads the configuration data and saves it to a map. Finally, it calls several functions for retrieving the value's datatype (int, string, etc). The detailed implementation can be seen below:
First define some ini configuration file some global constants:
Define some global constants for the `ini` configuration file:
var (
bComment = []byte{'#'}
@@ -140,7 +139,7 @@ Defines the format of the configuration file:
}
Defines a function parses the file, parses the file of the process is to open the file, and then read line by line, parse comments, blank lines, and key = value data:
Defines a function for parsing the file. The process begins by opening the file, then reading it line by line and parsing comments, blank lines and key=value data:
// ParseFile creates a new Config and parses the file configuration from the
// named file.
@@ -201,7 +200,7 @@ Defines a function parses the file, parses the file of the process is to open th
return cfg, nil
}
Below reads the configuration file to achieve a number of functions, the return value is determined as bool, int, float64 or string:
Below are a number of functions the parser uses for reading the configuration file. The return value is determined as either a bool, int, float64 or string:
// Bool returns the boolean value for a given key.
func (c *Config) Bool(key string) (bool, error) {
@@ -225,7 +224,7 @@ Below reads the configuration file to achieve a number of functions, the return
## Application guide
The following function is an example of the application, to access remote URL address Json data to achieve the following:
The following function is an example of an application I used to fetch json data from a remote url address:
func GetJson() {
resp, err := http.Get(beego.AppConfig.String("url"))
@@ -241,7 +240,7 @@ The following function is an example of the application, to access remote URL ad
}
}
Function calls the framework of the log function `beego.Critical` function is used to being given, called `beego.AppConfig.String(" url ")` is used to obtain the configuration information in the file, configuration files are as follows(app.conf ):
Beego's `Critical()` logging function is called to report any errors which may occur in the `GetJson()` function. `beego.AppConfig.String("url")` is used to obtain information from a configuration file (typically `app.conf`), which might look something like the following:
appname = hs
url ="http://www.api.com/api.html"
@@ -249,5 +248,5 @@ Function calls the framework of the log function `beego.Critical` function is us
## Links
- [Directory](preface.md)
- Previous section: [Design controllers](13.3.md)
- Next section: [Add, delete and update blogs](13.5.md)
- Previous section: [Designing controllers](13.3.md)
- Next section: [Adding, deleting and updating blogs](13.5.md)

View File

@@ -1,10 +1,10 @@
# 13.5 Add, delete and update blogs
# 13.5 Adding, deleting and updating blogs
Introduced in front beego framework to achieve the overall concept and the partial implementation of the pseudo- code, which subsections describe through beego build a blog system, including blog browse, add, modify, or delete operation.
We've already introduced the entire concept behind the Beego framework through examples and pseudo-code. This section will describe how to implement a blogging system using Beego, including the ability to browse, add, modify and delete blog posts.
## Blog directory
Blog directories are as follows:
Our blog's directory structure can be seen below:
/main.go
/views:
@@ -23,7 +23,7 @@ Blog directories are as follows:
## Blog routing
Blog main routing rules are as follows:
Our blog's main routing rules are as follows:
//Show blog Home
beego.RegisterController("/", &controllers.IndexController{})
@@ -38,7 +38,7 @@ Blog main routing rules are as follows:
## Database structure
The easiest database design blog information
A trivial database table to store basic blog information:
CREATE TABLE entries (
id INT AUTO_INCREMENT,

View File

@@ -1,6 +1,7 @@
# 13.6 Summary
In this chapter we describe how to implement a major foundation of the Go language framework, which includes routing design due to the built-in http Go package routing some shortcomings, we have designed a dynamic routing rule, and then introduces the MVC pattern Controller design, controller implements the REST implementation, the main ideas from the tornado frame, and then design and implement the template layout and automated rendering technology, mainly using the Go built-in template engine, and finally we introduce some auxiliary logs, configuration, etc. information design, through these designs we implemented a basic framework beego, present the framework has been open in GitHub, finally we beego implemented a blog system, through a detailed example code demonstrates how to quickly develop a site.
In this chapter, we described how to implement the major components of a Go web framework. We first designed a router to make up for some of shortcomings in Go's built-in `http` package, creating a router capable of dynamic routing and REST support. We also designed our own RESTful Controller class in accord with the principles of MVC, borrowing ideas from frameworks such as Tornado. Next, we designed and implemented a template layout and automated rendering system, mainly using Go's built-in templating engine. We then implemented a custom logger and talked about framework configuration to allow for flexible application deployment. Through this process, we have implemented a basic web framework called Beego which, at present, has been open-sourced on Github. Lastly, we implemented a simple blogging application on top of Beego. After having gone through all of these examples, you will hopefully have learned how to quickly develop websites in Go.
## Links

View File

@@ -1,8 +1,8 @@
# 14 Develop web framework
# 14 Developing a web framework
Chapter XIII describes how to develop a Web framework, by introducing the MVC, routing, log processing, the configuration process is completed a basic framework for the system, but a good framework requires some auxiliary tools to facilitate rapid development of Web, then we this chapter will provide some quick how to develop Web-based tools are introduced, the first section explains how to deal with static files, how to use existing open source twitter bootstrap for rapid development of beautiful sites, the second section describes how to use the previously described the session for user log in process, and the third section describes how convenient output forms that how data validation, how fast the data binding model for CRUD operations, the fourth section describes how to perform some user authentication, including http basic certification, http digest authentication, the fifth section describes how to use the previously described i18n support multi-language application development.
Chapter 13 described how to develop a web framework in Go. We introduced the MVC architecture, a routing and logging system system, and we also looked at simple server configuration. These are the basic building blocks of most frameworks, and it's a good start. However, for more sophisticated needs, some auxiliary tools are needed to facilitate rapid website development. In this chapter, we will provide some quick tips and tools for speeding up development. The first section will cover the how-to's how processing static files and we will be using Twitter's open source CSS and Javascript framework called Bootstrap for beautifying our website. The second section describes how to use the previously describe sessions for user login processing. Next, the third section describes how to generate forms, and how to process these forms for valid data. We will also talk about how to bind models for CRUD operations. In section 4, we'll describe how to perform some user authentication including basic HTTP authentication and HTTP digest authentication. Finally, the last section will talk about implementing the previously described i18n, to support multi-lingual web applications.
In this chapter expansion, beego framework will have rapid development of Web properties, and finally we will explain how to use the features of these extensions extension development blog system developed in Chapter XIII, through the development of a complete, beautiful blog system allows readers to understand beego development brings you fast.
By extending Beego in this chapter, we will be able to rapidly develop full stack web applications. Of course, we'll go through the features of these extensions step by step, applying them to the blogging system we developed in Chapter 13. Through the development of a complete and beautiful blogging system, users will hopefully be able to see how Beego can help to boost developer productivity.
## Links

View File

@@ -1,10 +1,10 @@
# 14.1 Static files
As we have already talked about how to deal with static files, this section we detail how to set up and use in beego static files inside. By then introduce a twitter open source html, css framework bootstrap, without a lot of design work we can let you quickly create a beautiful site.
We've already talked about how to deal with static files in previous sections. Now, let's look at how to set up and use static files inside of Beego. Then, through introducing Twitter's open source HTML and CSS framework Bootstrap, we'll be able quickly create beautiful looking websites without having to do much design work.o
## Beego static files and settings to achieve
## Beego static files and settings
Go's net/ http package provides a static file serving, `ServeFile` and `FileServer` other functions. beego static file processing is handled based on this layer, the specific implementation is as follows:
Go's `net/http` package provides a static file server with functions such as `ServeFile` and `FileServer`. Beego's static file handling is based on this layer, and its specific implementation is as follow:
//static file server
for prefix, staticDir := range StaticDir {
@@ -16,44 +16,44 @@ Go's net/ http package provides a static file serving, `ServeFile` and `FileServ
}
}
StaticDir is stored inside the corresponding URL corresponds to a static file directory, so handle URL requests when the request need only determine whether the address corresponding to the beginning of the process contains static URL, if included on the use http.ServeFile provide services.
`StaticDir` stores the URL which corresponds to a static file directory, so when handling requests, we simply need to determine whether or not the URL begins with a static file path. If so, we can simply respond using `http.ServeFile`.
Examples are as follows:
The following is an example:
beego.StaticDir["/asset"] = "/static"
Example. Then the request url `http://www.beego.me/asset/bootstrap.css` will request `/static/bootstrap.css` for the client.
Then, a request with a URL such as `http://www.beego.me/asset/bootstrap.css` will result in `/static/bootstrap.css` being served to the client.
## Bootstrap integration
Bootstrap is Twitter launched an open source toolkit for front-end development. For developers, Bootstrap is the rapid development of the best front-end Web application toolkit. It is a collection of CSS and HTML, it uses the latest HTML5 standard, to your Web development offers stylish typography, forms, buttons, tables, grids, systems, etc.
Bootstrap is a Twitter launched open source Toolkit for front-end development. For developers, Bootstrap is one of the best front end kits for rapid Web application development. It is a collection of HTML, CSS and javascript components, using the latest HTML5 standards. These include a responsive grid, forms, buttons, tables, and many other useful things.
- Components
Bootstrap contains a wealth of Web components, according to these components, you can quickly build a beautiful, fully functional website. Which includes the following components:
Pull-down menus, buttons, groups, buttons drop-down menus, navigation, navigation bar, bread crumbs, pagination, layout, thumbnails, warning dialog, progress bars, and other media objects
- JavaScript plugin
Bootstrap comes with 13 jQuery plug-ins for the Bootstrap a component gives"life." Including:
Modal dialog, tab, scroll bars, pop-up box and so on.
- Customize your own framework code
Bootstrap in can modify all CSS variables, according to their own needs clipping code.
Bootstrap contains a wealth of Web components. Using these components, you can quickly build a beautiful, fully functional website. Which includes the following components:
Pull-down menus, button groups, button drop-down menus, navigation, navigation bars, bread crumbs, pagination, layout, thumbnails, warning dialogs, progress bars, and other media objects
- JavaScript plugins
Bootstrap comes with 13 jQuery plug-ins for Bootstrap components, which gives them "life". These include:
Modal dialogs, tabs, scroll bars, pop-up boxes and so on.
- Bootstrap framework customization
All Bootstrap css variables can be modified according to your needs
![](images/14.1.bootstrap.png?raw=true)
Figure 14.1 bootstrap site
Figure 14.1 a bootstrap website
Next, we use the bootstrap into beego frame inside, quickly create a beautiful site.
Next, let's see how we can use Bootstrap inside our Beego application to quickly create a beautiful website:
1. First to download the bootstrap directory into our project directory, named as static, as shown in the screenshot.
1. First, let's download the bootstrap directory into our project's static directory, as shown in the following screenshot:
![](images/14.1.bootstrap2.png?raw=true)
Figure 14.2 Project static file directory structure
2. Because beego default values set StaticDir, so if your static files directory is static, then you need not go any further:
2. Because Beego sets a default value for `StaticDir`, if your static files directory is `static`, then you need not go any further:
StaticDir["/static"] = "static"
3. templates use the following address on it:
3. Our templates use the following asset paths:
// css file
<link href="/static/css/bootstrap.css" rel="stylesheet">
@@ -64,16 +64,16 @@ Next, we use the bootstrap into beego frame inside, quickly create a beautiful s
// Picture files
<img src="/static/img/logo.png">
The above can be achieved to bootstrap into beego in the past, as demonstrated in Figure is the integration of the show came after renderings:
With the above code, we are integrating Bootstrap into our Beego application. The figure below demonstrates the rendered page:
![](images/14.1.bootstrap3.png?raw=true)
Figure 14.3 Construction site interface based bootstrap
Figure 14.3 website integrated with Bootstrap
These templates and formats bootstrap official has to offer will not be repeated here paste code, we can bootstrap on the official website to learn how to write templates.
These templates and formats are come shipped with Bootstrap so we won't repeat the complete code here, however you can take a look at the project's official page to learn how to write your own templates.
## Links
- [Directory](preface.md)
- Previous section: [Develop web framework](14.0.md)
- Next section: [Session](14.2.md)
- Previous section: [Developing a web framework](14.0.md)
- Next section: [Sessions](14.2.md)

View File

@@ -1,19 +1,20 @@
# 14.2 Session
# 14.2 Sessions
Chapter VI, when we saw how to use the Go language session, also achieved a sessionManger, beego sessionManager based framework to achieve a convenient session handling functions.
In chapter 6, we introduced some basic concepts pertaining to sessions in Go, and we implemented a sessions manager. The Beego framework uses this session manager to implement some convenient session handling functionality.
## Session integration
beego mainly in the following global variables to control the session handling:
## Integrating sessions
Beego handles sessions mainly according to the following global variables:
// related to session
SessionOn bool // whether to open the session module, the default is not open
SessionProvider string // session backend processing module provided, the default is sessionManager supported memory
SessionName string // client name saved in cookies
SessionGCMaxLifetime int64 // cookies validity
SessionOn bool // whether or not to open the session module. Defaults to false.
SessionProvider string // the desired session backend processing module. Defaults to an in-memory sessionManager
SessionName string // the name of the client saved cookies
SessionGCMaxLifetime int64 // cookie validity
GlobalSessions *session.Manager// global session controller
Of course, the above values of these variables need to be initialized, you can also follow the code to match the configuration file to set these values:
Of course, the above values of these variables need to be initialized. You can also use the values from the following configuration file code to set these values:
if ar, err := AppConfig.Bool("sessionon"); err != nil {
SessionOn = false
@@ -37,32 +38,33 @@ Of course, the above values of these variables need to be initialized, you can a
SessionGCMaxLifetime = 3600
}
In beego.Run function to add the following code:
Add the following code in the `beego.Run` function:
if SessionOn {
GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime)
go GlobalSessions.GC()
}
So long SessionOn set to true, then it will open the session by default function to open an independent goroutine to handle session.
As long as `SessionOn` is set to true, it will open the session by default with an independent goroutine session handler
In order to facilitate our custom Controller quickly using session, the author `beego.Controller` provides the following methods:
To assist us in quickly using sessions in a custom Controller, `beego.Controller` provides the following method:
func (c *Controller) StartSession() (sess session.Session) {
sess = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request)
return
}
## Session using
## Using sessions
Through the above code we can see, beego framework simply inherit the session function, then how to use it in your project ?
From the code above, we can see that the Beego framework simply inherits its session functionality. So, how do we use it in our projects?
First, we need to apply the main entrance open session:
First of all, we need to open the session at the entry point of our application.
beego.SessionOn = true
We can then corresponding method in the controller to use the session as follows: the
We can then use the corresponding session method inside our controller like so:
func (this *MainController) Get() {
var intcount int
@@ -81,14 +83,14 @@ We can then corresponding method in the controller to use the session as follows
this.TplNames = "index.tpl"
}
The above code shows how to use the control logic session, mainly divided into two steps:
The code above shows how to use sessions in the controller logic. The process can be divided into two steps:
1. Get session object
1. Getting session object
// Get the object, similar in PHP session_start()
sess:= this.StartSession()
2. to use the session for general session value operation
2. Using the session for general operations
// Get the session values , similar in PHP $ _SESSION ["count"]
sess.Get("count")
@@ -96,10 +98,10 @@ The above code shows how to use the control logic session, mainly divided into t
// Set the session value
sess.Set("count", intcount)
As can be seen from the above code beego framework based applications developed using the session quite easy, basically, and PHP to call `session_start()` similar.
As you can see, applications based on the Beego framework can easily implement sessions. The process is very similar to calling `session_start()` in PHP applications.
## Links
- [Directory](preface.md)
- Previous section: [Static files](14.1.md)
- Next section: [Form](14.3.md)
- Next section: [Forms](14.3.md)

View File

@@ -1,27 +1,33 @@
# 14.3 Form
# 14.3 Forms
In Web Development For such a process may be very familiar:
In web development, the following workflow will probably look quite familiar:
- Open a web page showing the form.
- Users fill out and submit the form.
- If a user submits some invalid information, or you might have missed a required item, the form will be together with the user's data and the error description of the problem to return.
- Users fill in again to continue the previous step process until the submission of a valid form.
- Open a web page showing a form
- Users fill out and submit the form
- If a user submits some invalid information or has neglected to fill out a required field, the form will be returned to the user (along with the filled in data) with some descriptive information about the problem.
- Users re-fill the invalid fields and continue attempting to submit the form until it's accepted
At the receiving end, the script must:
- Check the user submitted form data.
- Verify whether the data is the correct type, the appropriate standard. For example, if a user name is submitted, it must be verified whether or contains only characters allowed. It must have a minimum length can not exceed the maximum length. User name can not already exist with others duplicate user name, or even a reserved word and so on.
- Filtering data and clean up the unsafe character that guarantees a logic processing received data is safe.
- If necessary, pre-formatted data( or data gaps need to be cleared through the HTML coding and so on. )
- Preparing the data into the database.
- Verify whether the data is the correct type and of the appropriate standard. For example, if a username is submitted, it must verify that it contains only valid characters. Other examples would be checking for minimum and maximum lengths, username uniqueness, and so on.
- Filtering data and cleaning up unsafe characters to guarantee that our application only processes data which is safe.
- If necessary, pre-format the data (or data gaps need to be cleared through the HTML coding and so on.)
- Prepare the data for insertion into the database
While the above process is not very complex, but usually need to write a lot of code, and in order to display an error message on the page often use a variety of different control structures. Create a form validation, although simple to implement it boring.
Although the procedure is not very complex, it usually requires a lot of boilerplate. In addition, web applications often use a variety of different control structures to display error messages on returned pages. Implementing form validation is a simple but boring task.
## Forms and validation
For developers, the general development process can be quite complex, but it's mostly repetitive work. Suppose a scenario arises where you suddenly need to add a form to your project, causing you to rewrite all of the local code tied in with the form. We know that `structs` are a very commonly used data structure in Go, and Beego uses them to its advantage for processing form information.
First, we define a `struct` with fields corresponding to the fields in our form element. We can use `struct` tags which map to the form element, as shown below:
First define a struct that corresponds to when developing Web applications, a field corresponding to a form element, defined by using a struct tag corresponding to the element information and authentication information, as shown below:
For developers, the general development process is very complex, and mostly are repeating the same work. Assuming a scenario project suddenly need to add a form data, then the local code of the entire process needs to be modified. We know that Go inside a struct is a common data structure, so beego the form struct used to process form information.
First define a developing Web applications corresponding struct, a field corresponds to a form element, through the struct tag to define the corresponding element information and authentication information, as follows:
First define a `struct` with fields corresponding to our form element, using `struct` tags to define corresponding element and authentication information, like so:
type User struct{
Username string `form:text,valid:required`
@@ -31,7 +37,7 @@ First define a developing Web applications corresponding struct, a field corresp
Introduce string `form:textarea`
}
Struct defined in this way after the next operation in the controller
After defining our `struct`, we can add this action in our controller:
func (this *AddController) Get() {
this.Data["form"] = beego.Form(&User{})
@@ -39,14 +45,14 @@ Struct defined in this way after the next operation in the controller
this.TplNames = "admin/add.tpl"
}
This form is displayed in the template
The form is displayed in our template like so:
<h1>New Blog Post</h1>
<form action="" method="post">
{{.form.render()}}
</form>
Above we defined the entire first step to display the form from the struct process, the next step is the user fill out the information, and then verify that the server receives data, and finally into the database.
Above, we've defined the entire first step of displaying a form mapped to a `struct`. The next step is for users to fill in their information and submit the form, after which the server will receive the data and verify it. Finally, the record will be inserted into the database.
func (this *AddController) Post() {
var user User
@@ -60,7 +66,7 @@ Above we defined the entire first step to display the form from the struct proce
## Form type
The following list to the corresponding form element information:
The following table lists the corresponding form element information:
<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder">
<tbody>
@@ -135,9 +141,9 @@ The following list to the corresponding form element information:
</table>
## Forms authentication
## Form validation
The following list may be used are listed rules native:
The following table lists some form validation rules native to Beego that can be used:
<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder">
<tbody>
@@ -345,6 +351,6 @@ The following list may be used are listed rules native:
## Links
- [Directory](preface.md)
- Previous section: [Session](14.2.md)
- Previous section: [Sessions](14.2.md)
- Next section: [User validation](14.4.md)

View File

@@ -1,21 +1,20 @@
# 14.4 User validation
In the process of developing Web applications, user authentication is frequently encountered problems developers, user log in, registration, log out and other operations, and the general certification is also divided into three aspects of certification
In the process of developping web applications, user authentication is a problem which developers frequently encounter. User login, registration and logout, among other operations, as well as general authentication can also divided into three parts:
- HTTP Basic and HTTP Digest Authentication
- Third Party Certified Integration: QQ, micro-blogging, watercress, OPENID, Google, GitHub, Facebook and twitter, etc.
- Custom user log in, registration, log out, are generally based on session, cookie authentication
- HTTP Basic, and HTTP Digest Authentication
- Third Party Authentication Integration: QQ, micro-blogging, watercress, OPENID, Google, GitHub, Facebook and twitter, etc.
- Custom user login, registration, logout, are generally based on sessions and cookie authentication
beego There is no way for any of these three forms of integration, but can make use of third party open source library to achieve the above three methods of user authentication, but the first two subsequent authentication beego be gradually integrated.
Beego does not natively provide support for any of these three things, however you can easily make use of existing third party open source libraries to implement them. The first two authentication solutions are on Beego's roadmap to eventually be integrated.
## HTTP basic and digest authentication
These two certifications are some applications using relatively simple authentication, there are already open source third-party library supports both authentication:
Both HTTP basic and digest authentication are relatively simple techniques commonly used by web applications. There are already many open source third-party libraries which support these two authentication methods, such as:
github.com/abbot/go-http-auth
The following code demonstrates how to use this library in order to achieve the introduction of beego Certification:
The following code demonstrates how to use this library to implement authentication in a Beego application:
package controllers
@@ -49,22 +48,22 @@ The following code demonstrates how to use this library in order to achieve the
this.TplNames = "index.tpl"
}
The above code takes advantage of beego the prepare function in the normal logic function is called before the certification, so it is very simple to achieve a http auth, digest authentication is the same principle.
The above code takes advantage of Beego's `prepare()` function to perform authentication before allowing the normal flow of execution to proceed; as you can see, it's very simple to implement HTTP authentication. Digest authentication can be implemented in much the same way.
## OAuth and OAuth 2 certification
## OAuth and OAuth 2 authentication
OAuth and OAuth 2 is currently more popular two authentication methods, but fortunately, there is a third-party library to achieve this certification, but it is realized abroad, and did not QQ, microblogging like domestic application certified integration:
OAuth and OAuth 2 are currently two of the most popular authentication methods. Fortunately, there are third-party libraries which implement this type of authentication such as the `go.auth` package available on github.
github.com/bradrydzewski/go.auth
The following code demonstrates how to put the library in order to achieve the introduction of beego OAuth authentication, an example to demonstrate GitHub here:
The code below demonstrates how to use this library to implement OAuth authentication in Beego using our Github credentials:
1. Add two routes
1. Let's add some routes
beego.RegisterController("/auth/login", &controllers.GithubController{})
beego.RegisterController("/mainpage", &controllers.PageController{})
2. Then we deal GithubController landing page:
2. Then we deal with the `GithubController` landing page:
package controllers
@@ -93,7 +92,7 @@ The following code demonstrates how to put the library in order to achieve the i
githubHandler.ServeHTTP(this.Ctx.ResponseWriter, this.Ctx.Request)
}
3. treatment after successful landing pages
3. Handling after a successful landing page:
package controllers
@@ -130,27 +129,29 @@ The following code demonstrates how to put the library in order to achieve the i
this.TplNames = "home.tpl"
}
The whole process is as follows, first open your browser and enter the address:
The whole process is as follows:
first open your browser and enter the address:
![](images/14.4.github.png?raw=true)
Figure 14.4 shows the home page with a log in button
Figure 14.4 shows the home page with a login button
Then click on the link following screen appears:
When clicking on the link, the following screen appears:
![](images/14.4.github2.png?raw=true)
Figure 14.5 is displayed after clicking the log in button authorization GitHub page
Figure 14.5 displayed after clicking the login button to authenticate with your GitHub credentials
Then click Authorize app will appear the following interface:
After clicking "Authorize app", the following screen appears:
![](images/14.4.github3.png?raw=true)
Figure 14.6 is displayed after log in authorization to obtain information page GitHub
Figure 14.6 authorized Github information gets displayed after the login page
## Custom authentication
Custom authentication and session are generally a combination of proven, the following code from an open source based beego blog:
Custom authentication is generally combined with session authentication; the following code is a Beego based open source blog which demonstrates this:
//Login process
func (this *LoginController) Post() {
@@ -243,7 +244,7 @@ Custom authentication and session are generally a combination of proven, the fol
return true
}
With the user log in and registration, where you can add other modules such as the judgment of whether the user log in:
Once you have implemented user login and registration, other modules can be added to determine whether the user has been logged in or not:
func (this *AddBlogController) Prepare() {
sess := globalSessions.SessionStart(this.Ctx.ResponseWriter, this.Ctx.Request)

View File

@@ -1,16 +1,16 @@
# 14.5 Multi-language support
We introduced in Chapter internationalization and localization, we developed a go-i18n library, the library this section we will integrate beego frame inside, making our framework supports internationalization and localization.
In the chapter where we introduced internationalization and localization, we developed the `go-i18n` library. In this section, we will see how this library is integrated into the Beego framework, and how it enables our Beego applications to support both internationalization and localization.
## I18n integration
beego global variable is set as follows:
Beego first sets some global variables:
Translation i18n.IL
Lang string // set the language pack, zh, en
LangPath string // set the language pack location
Multi-language function to initialize:
A multi-language initialization function is defined:
func InitLang(){
beego.Translation:=i18n.NewLocale()
@@ -18,7 +18,7 @@ Multi-language function to initialize:
beego.Translation.SetLocale(beego.Lang)
}
In order to facilitate more direct call in the template language pack, we have designed three functions to handle the response of multiple languages:
In order to facilitate multi-language calls in the template package directly, we designed three functions for handling multi-language responses:
beegoTplFuncMap["Trans"] = i18n.I18nT
beegoTplFuncMap["TransDate"] = i18n.I18nTimeDate
@@ -60,17 +60,17 @@ In order to facilitate more direct call in the template language pack, we have d
return beego.Translation.Money(s)
}
## Use multi-language development
## Multi-language development
1. Set the location of language and language packs, then initialize the i18n objects:
1. Setting the language and location of the language pack, then initialize i18n objects:
beego.Lang = "zh"
beego.LangPath = "views/lang"
beego.InitLang()
2. Design Multi-language Pack
2. Designing a multi-language package
The above talked about how to initialize multi language pack, the language pack is now designing multi, multi-language package is json file, as described in Chapter X, we need to design a document on LangPath following example zh.json or en.json
Above, we talked about how to initialize a multi-language package. Now, let's look at how to design one. Multi-language packages are typically JSON files, as you've already seen in Chapter 10. We must provide translation files for languages we wish to support on our `LangPath`, such as the following:
# zh.json
@@ -90,16 +90,16 @@ In order to facilitate more direct call in the template language pack, we have d
}
}
3. Use the Language Pack
3. Using language packages
We can call the controller to get the response of the translation language translation, as follows:
We can call the controller to get the translated response in the desired language, like so::
func (this *MainController) Get() {
this.Data["create"] = beego.Translation.Translate("create")
this.TplNames = "index.tpl"
}
We can also directly call response in the template translation function:
We can also directly interpolate translated responses in our templates:
// Direct Text translation
{{.create | Trans}}

View File

@@ -1,25 +1,25 @@
# 14.6 pprof
Go language has a great design is the standard library with code performance monitoring tools, there are packages in two places:
A great feature of Go's standard library is its code performance monitoring tools. These packages exist in two places:
net/http/pprof
runtime/pprof
In fact, `net/http/pprof` in just using `runtime/pprof` package for packaging a bit, and exposed on the http port
In fact, `net/http/pprof` simply exposes runtime profiling data from the `runtime/pprof` package on an HTTP port.
## Beego support pprof
## pprof support in Beego
Currently beego framework adds pprof, this feature is not turned on by default, if you need to test performance, view the execution goroutine such information, in fact, Go's default package "net/http/pprof" already has this feature, and if Go manner in accordance with the default Web, you can use the default, but because beego repackaged ServHTTP function, so if you can not open the default includes this feature, so the need for internal reform beego support pprof.
The Beego framework currently supports pprof, however it is not not turned on by default. If you need to test the performance of your application, (for instance by viewing the execution goroutine such information, in fact, Go's default package "net/http/pprof" already has this feature, and if Go manner in accordance with the default Web, you can use the default, but because beego repackaged ServHTTP function, so if you can not open the default includes this feature, so the need for internal reform beego support pprof.
- First in beego.Run function automatically according to whether the variable load performance pack
- First in our `beego.Run` function, we choose whether or not to automatically load the performance pack according to our configuration variable (in this case, PprofOn):
if PprofOn {
BeeApp.RegisterController(`/debug/pprof`, &ProfController{})
BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{})
}
- Design ProfConterller
- Designing `ProfController`
package beego
@@ -50,27 +50,27 @@ Currently beego framework adds pprof, this feature is not turned on by default,
## Getting started
Through the above design, you can use the following code to open pprof:
From the above, we can see that enabling pprof is as simple as setting the `PprofOn` configuration variable to `true`:
beego.PprofOn = true
Then you can open in a browser the following URL to see the following interface:
You can then open the following URL in your browser to see the following interface:
![](images/14.6.pprof.png?raw=true)
Figure 14.7 current system goroutine, heap, thread information
Click goroutine we can see a lot of detailed information:
By clicking on a goroutine, we can see a lot of detailed information:
![](images/14.6.pprof2.png?raw=true)
Figure 14.8 shows the current goroutine details
We can also get more details from the command line information
Of course, we can also get more details from the command line:
go tool pprof http://localhost:8080/debug/pprof/profile
This time the program will enter the profile collection time of 30 seconds, during which time desperately to refresh the page on the browser, try to make cpu usage performance data.
This time, the program will begin profiling the application for a period of 30 seconds, during which time it will repeatedly refresh the page in the browser in an attempt to gather CPU usage and performance data.
(pprof) top10

View File

@@ -1,6 +1,6 @@
# 14.7 Summary
This chapter explains how to extend the framework based on beego, which includes support for static files, static files, mainly about how to use beego for rapid web development using bootstrap to build a beautiful site; second summary explaining how beego in integrated sessionManager, user-friendly in use beego quickly when using session; Third Summary describes the forms and validation, based on the Go language allows us to define a struct in the process of developing Web from repetitive work of liberation, and joined the after verification of data security can be as far as possible, the fourth summary describes the user authentication, user authentication, there are three main requirements, http basic and http digest certification, third party certification, custom certification through code demonstrates how to use the existing section tripartite package integrated into beego applications to achieve these certifications; fifth section describes multi-language support, beego integrated go-i18n this multi-language pack, users can easily use the library develop multi-language Web applications; section six subsections describe how to integrate Go's pprof packages, pprof package is used for performance debugging tools, after the transformation by beego integrated pprof package, enabling users to take advantage of pprof test beego based applications developed by these six subsections introduces us to expand out a relatively strong beego framework that is sufficient to meet most of the current Web applications, users can continue to play to their imagination to expand, I am here only a brief introduction I can think of to compare several important extensions.
This chapter illustrates some ways in which the Beego framework can be extended. We first looked at static file support, learning how Beego handles serving static files internally. We saw how this functionality allowed us to easily integrate static assets (such as Bootstrap's CSS files) for rapid and great looking website development. Next, we saw how to integrate `sessionManager` to painlessly facilitate user sessions in Beego. We then described form management and validation, leveraging Go's structs to reduce code repetition and for simplifying field validation. After that, we discussed user authentication which involved three main strategies: HTTP authentication (basic and digest), third party authentication, and custom authentication. We learned about some existing third party authentication packages that have already implemented these strategies, which are conveniently accommodated by Beego. The next section re-introduced language support in Beego; we saw how to integrate the `go-i18n` package and learned how to easily load multiple language packs into our applications as needed. Lastly, we discussed how to work with Go's `pprof` packages in Beego. The `pprof` package is used for performance profiling in Go, and Beego repackages it so it can serve the same purpose in Beego applications without much additional work. Through these six sections, we've extended Beego with many features, making it into a versatile framework suitable for the requirements of many web applications. Users have the freedom of extending the framework to suit their individual needs; this brief introduction to Beego simply offers a small taste of what can be done!
## Links

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 24 KiB