User Registration, login, and cancellation are inevitable functions of any website. It can be said that this is a field that involves a lot of new things, and every website maker should have done it many times. You can see most of the Web frameworks in use from such a small function.
Today, let's use this basic module to look at revel.
First, sort out the technical framework and components we have selected:
Web Framework: revel
Database: MongoDB
Database DRIVER: MgO
To do a good job, you must first sharpen the tool. Here we recommend a MongoDB GUI client-mongovue. It can be said that without this tool, we will suffer a lot during the development process.
Assume that you have the most basic knowledge about the Go language and have configured goroot and gopath.
First, run the following command under gopath to install revel and compile the revel tool.
Go get github.com/robfig/revel
Go build-O bin/revel.exe github.com/robfig/revel/revel
After that, go to gopath \ binto check that revel.exe has been compiled. For ease of use, I added gopath \ bin to the environment variable path.
Run it where you want to store project files
Revel new MyApp
The entire project framework has been established. You can see from the folder structure below that revel is an MVC framework.
Now the entire project can be run. Run the following command line to start the site.
Revel run MyApp
Open the browser http: // 127.0.0.1: 9000 and you will see the following results
The internal details are not mentioned at the moment. Come on and let the user register first. Note that you do not need to restart revel during the entire development process.
1. Prepare the Model
According to the MVC development pace, we should first prepare the model. Create a new models directory under the app directory, and then create entity. Go (the name of this file can be customized) in it. Open entity. Go and add the object definition of user.
Type User struct {
Email string
Nickname string
Password [] Byte
}
Type mockuser struct {
Email string
Nickname string
Password string
Confirmpassword string
}
Why define mockuser? The cause will be mentioned later.
Write the Dal (data access layer) and create the Dal. Go in the app \ models directory. The writing of Dal can actually use the revel plug-in mechanism. To avoid introducing too many concepts at once, use this simple method first.
Package Models
Import (
"Github.com/robfig/revel"
"Labix.org/v2/mgo"
)
Const (
Dbname = "MyApp"
Usercollection = "user"
)
Type Dal struct {
Session * MgO. Session
}
Func newdal () (* Dal, error ){
Revel. config. setsection ("DB ")
IP, found: = revel. config. String ("ip ")
If! Found {
Revel. Error. Fatal ("cannot load database IP from app. conf ")
}
Session, err: = MgO. Dial (IP)
If Err! = Nil {
Return nil, err
}
Return & Dal {session}, Nil
}
Func (D * DAL) Close (){
D. session. Close ()
}
Revel already provides the configuration system. Open conf \ app. conf and add the following content.
[DB]
IP = 127.0.0.1
Add the dal_account.go file in the app \ models directory. The Code is as follows.
Func (D * DAL) registeruser (MU * mockuser) error {
UC: = D. session. dB (dbname). C (usercollection)
// Check whether the email and nickname have been used.
I, _: = UC. Find (m {"nickname": mu. Nickname}). Count ()
If I! = 0 {
Return errors. New ("the user nickname has been used ")
}
I, _ = UC. Find (m {"email": mu. Email}). Count ()
If I! = 0 {
Return errors. New ("the email address has been used ")
}
VaR U user
U. Email = mu. Email
U. Nickname = mu. Nickname
U. Password, _ = bcrypt. generatefrompassword ([] Byte (MU. Password), bcrypt. defaultcost)
Err: = UC. insert (u)
Return err
}
Does it show the meaning of the existence of mockuser? The user enters a plaintext password on the page, which cannot be directly stored in the database. encryption is required first. Here the "code.google.com/p/go.crypto/bcrypt" library is used.
2. Prepare Controller
Prepare the controller and create an account. Go file in APP \ controllers to implement the account controller. The Code is as follows.
Package Controllers
Import (
"Github.com/robfig/revel"
"MyApp/APP/models"
)
Type account struct {
* Revel. Controller
}
Func (C * account) Register () revel. Result {
Return C. Render ()
}
Func (C * account) postregister (User * models. mockuser) revel. Result {
Return C. Render ()
}
3. Add a route
Prepare the route, open conf \ routes, and add the register URL ing.
# Routes
# This file defines all application routes (higher priority routes first)
#~~~~
Module: testrunner
GET/APP. Index
GET/register account. Register
Post/register account. postregister
# Ignore favicon requests
GET/favicon. ICO 404
# Map static resources from the/APP/public folder to the/Public path
GET/public/* filepath static. Serve ("public ")
# Catch all
*/: Controller/: Action: controller.: Action
Assume that everyone knows what restful means. Here we map the two URLs to the two actions of the controller.
We can see that all the mappings between URLs and controllers are defined here, which is very convenient. This file will be converted to app \ routes. Go before running. The content in this file needs to be used later when talking about reverseredirect.
4. Prepare View
Prepare the view and create a new file register.html under app \ views. the key content is as follows:
<Form action = "{URL" account. postregister "}" method = "Post">
{With $ field: = field "user. Email ".}}
<Div class = "control-group {{$ field. errorclass }}">
<Label class = "control-label" for = "{$ field. ID}"> email </label>
<Div class = "controls">
<Input type = "email" id = "{$ field. id} "name =" {$ field. name }}" value = "{$ field. flash} "required>
{If $ field. Error }}
<SPAN class = "Help-inline" >{{$ field. Error }}</span>
{End }}
</Div>
</Div>
{End }}
...
1.1: explain the meaning of the above blue keywords.
URL is a template function provided by revel. You can easily change the Controller action to a relative URL. The operating principle of URL is to find it in the defined routes ing.
Field is a template function provided by revel. It is used to generate a form. Do you still remember the signature of the postregister method?
Func (C * account) postregister (User * models. mockuser) revel. Result
It accepts a * models named user. user-type parameters. Therefore, use {with $ field: = field "user. email "} to notify revel to encapsulate form parameters in the user structure and then pass them to postregister.
We all know that the value entered during User Registration requires a validity test. When the value entered by the user does not conform to the standard, an error message is prompted, which is usually shown below:
$ Field. errorclass is used to conveniently display the error status on the page by adding a class when this parameter is incorrect. The errorclass value can be modified using the following code.
Revel. error_class = "error"
$ Field. ID and $ field. name are not explained. You will see the generated source code in your browser later.
$ Field. Flash: here we need to explain the concept of flash.
Flash is a dictionary used to transmit data between two requests. data is stored in cookies.
As we all know, the HTTP protocol itself is stateless. Therefore, in this case, the user entered an invalid email address during registration and clicked "register" to refresh the page, there is a red line under "email": "The email address you entered is invalid." At this moment, the value entered by the last user must appear in the text box. Then, $ field. Flash searches for the value with $ field. name as the key in flash.
$ Field. Error indicates the value of $ field. name_error as the key in flash, that is, the red "password must be greater than or equal to 6 bits" error message.
Now, add "nickname", "password", and "Confirm Password" to the view according to this rhythm.
Visit http: // 127.0.0.1/register. Is that true?
Revelwill go through the name of controller.actionto find the viewfile with the same name. For example, the register.html corresponds to register.html. Here, you need to note that revel searches for the caller of the controller. Render method through reflection, and only looks up one layer.
For example, the following code cannot work.
Func (C * account) somemethod () revel. Result {
...
Return C. Render ()
}
Func (C * account) Register () revel. Result {
Return C. somemethod ()
}
5. Implement Controller
Now let's add the registration processing logic for postregister.
First, verify the validity of the parameter.
Func (C * account) postregister (User * models. mockuser) revel. Result {
C. validation. Required (User)
C. validation. Email (user. Email)
C. validation. Required (user. Nickname)
C. validation. Required (user. Password)
C. validation. Required (user. confirmpassword = user. Password)
If C. validation. haserrors (){
C. flashparams ()
Return C. Redirect (* account). Register)
}
Return C. Render ()
}
Revel provides a very useful validation mechanism. The above code should not need to be explained too much, but only one line
C. flashparams ()
Its function is to save the parameters submitted by form to flash as they are. Do you still remember $ field. Flash?
Now, go to the registration page and enter some incorrect values to check the response. Well, you should soon find that although the error information has been displayed, it is a pity that it is in English, modify it.
Func (C * account) postregister (User * models. mockuser) revel. Result {
C. validation. Email (user. Email). Message ("invalid email format ")
C. validation. Required (user. Nickname). Message ("user nickname cannot be blank ")
C. validation. Required (user. Password). Message ("the password cannot be blank ")
C. validation. Required (user. confirmpassword = user. Password). Message ("the two passwords are inconsistent ")
If C. validation. haserrors (){
C. flashparams ()
Return C. Redirect (* account). Register)
}
Return C. Render ()
}
Validation provides several common verification methods, which can be easily understood.
When all parameter checks are passed, the Dal. registeruser method is called to store user information to the database.
Func (C * account) postregister (User * models. mockuser) revel. Result {
C. validation. Email (user. Email). Message ("invalid email format ")
C. validation. Required (user. Nickname). Message ("user nickname cannot be blank ")
C. validation. Required (user. Password). Message ("the password cannot be blank ")
C. validation. Required (user. confirmpassword = user. Password). Message ("the two passwords are inconsistent ")
If C. validation. haserrors (){
C. flashparams ()
Return C. Redirect (* account). Register)
}
Dal, err: = models. newdal ()
If Err! = Nil {
C. Response. Status = 500
Return C. rendererror (ERR)
}
Defer Dal. Close ()
Err = Dal. registeruser (User)
If Err! = Nil {
C. Flash. Error (ERR. Error ())
Return C. Redirect (* account). Register)
}
Return C. Redirect (* account). registersuccessful)
}
Func (C * account) registersuccessful () revel. Result {
Return C. Render ()
}
I added the registersuccessful method to show that the registration is successful. Do not forget to add the corresponding items in routes and view.
So far, user registration has been completed. I don't know if you noticed it. Even if you modify the go code, you still don't need to restart revel. Refresh the browser page and you will find that the new Code has been automatically compiled and enabled.
This article describes the significance of revel.exe. It monitors file modifications throughout the project, and then automatically compiles and runs the program. It feels as comfortable as using Python and Ruby during development.
I have already mentioned many knowledge points about revel. I hope it will be useful to you. Please feel free to ask any questions!
Finally, we use revel to write our entrepreneurial product Shan Po. This is a proven framework.