Go language Combat-user registration when starting a business

Source: Internet
Author: User
Tags email string mongodb gui
This is a creation in Article, where the information may have evolved or changed.

User registration, login and logout is the function that any website must have, it can be said, this is to reinvent the wheel to do many fields, each person who makes the website should have done a lot of times. See around corners, from such a small feature, you can actually see most of the Web framework you are using.

Let's take a look at Revel today with this basic module.

Let's start by sorting out the technical frameworks and components we use:

Web framework: Revel

Database: MongoDB

Database Driver:mgo

工欲善其事, its prerequisite, here focuses on a MongoDB GUI client-Mongovue, which can be said that without this tool, we will suffer many many in the process of development.

Assuming that you already have the most basic knowledge of the go language, you have already 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 completion go to Gopath\bin below to see if it has been compiled revel.exe. For ease of use, I added the gopath\bin to the environment variable path.

Run where you want the project files to be stored

Revel New MyApp

The entire project framework is set up, look at the following folder structure can be seen, Revel is an MVC framework.

At this point the entire project can be run, run the following command line to start the site.

Revel Run MyApp

Open your browser http://127.0.0.1:9000 and you'll see the following results

The internal details are not much said, come on, let the user register first. Note that you do not need to restart Revel most of the time throughout the development process.

1. Prepare the Model

According to the MVC development Rhythm, we first prepare the model. Create a new models directory in the app directory, then create a new Entity.go (the name of this file can help yourself), open entity.go to join the user's entity definition.

Type User struct {
Email string
Nickname string
Password []byte
}

Type Mockuser struct {
Email string
Nickname string
Password string
ConfirmPassword string
}

Why define Mockuser? The reason is mentioned later.

Now write the DAL (data access layer) and create a new dal.go in the App\models directory. The Dal can actually be written in a Revel plug-in mechanism, here in order to avoid introducing too many concepts, first in this simple way.

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 provided the configuration system, open conf\app.conf, add the following content

[db]
IP = 127.0.0.1

Now implement the registration needs to use the method, in the App\models directory to add the file Dal_account.go, the code is as follows.

Func (d *dal) RegisterUser (mu *mockuser) error {
UC: = d.session.db (DbName). C (usercollection)

Check if email and nickname are already in use
I, _: = UC. Find (m{"nickname": Mu. Nickname}). Count ()
If I! = 0 {
return errors. New ("User nickname is already in use")
}

I, _ = UC. Find (m{"email": mu. Email}). Count ()
If I! = 0 {
return errors. New ("email address already in use")
}

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
}

Do you see the meaning of Mockuser existence? Users in the page is filled with the plaintext password, which can not be directly stored in the database, the need to encrypt first, where the "Code.google.com/p/go.crypto/bcrypt" this library.

2. Prepare the Controller

Prepare the controller, create a new file Account.go in the App\controllers, implement the account controller inside, 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 route

Prepare the route, open conf\routes, and add the Register's URL mapping.

# 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

Assuming that everyone knows what restful means, here is the two URL mapped to the controller's two action.

As you can see, it is convenient to define the mappings between all URLs to the controller. This file will be Revel converted to app\routes\routes.go file to participate in the compilation before it is run. The contents of this file need to be used in the later reverseredirect.

4. Prepare the View

Prepare view, create a new file under App\views register.html, 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 points explain the meaning of the Blue keyword above.

URL is a template function provided by Revel, it is convenient to change the controller's action to a relative URL, it works in fact to go to the definition of the routes mapping inside the lookup.

field is a template function provided by Revel, specifically to facilitate the generation of form, remember the signature of the Postregister method?

Func (c *account) postregister (user *models. Mockuser) Revel. Result

It accepts a *models named user. parameter of the user type, so use {{with $field: = Field ' user. Email "}} can notify Revel to encapsulate the parameters of the form into the user structure and pass it to Postregister.

We all know the user registration time to fill in the value of the need to do a validation, when the user fill in the values do not meet the standard needs to appear error, usually the following

$field. The function of Errorclass is that when this parameter is wrong, it is convenient to display the error status on the page by adding class. The value of Errorclass can be modified by the following code.

Revel. Error_class = "Error"

$field. ID and $field. Name does not explain, you can open a browser later to see the generated source code to understand.

$field. Flash here needs to explain the concept of flash.

Flash is a dictionary for passing data in the middle of two request data stored in a cookie.

As we all know, the HTTP protocol itself is stateless, so, consider this use case, the user entered an invalid email address at the time of registration, click the registration page refreshed a bit, "e-mail" Below a line of red words "you entered an invalid email address", The last user input value appears in the text box at this moment. Well, $field. Flash is in flash to find to $field. Name is the value of key.

$field. The error is to find $field in Flash. Name_error is the value of key, that is, the "password must be greater than or equal to 6 bits" in red in the error message.

OK, now let's follow this rhythm and add "nickname", "Password" and "Confirm password" to the view.

Once added, go to visit http://127.0.0.1/register. Isn't that so?

Revel will look up the name of the view file by Controller.action, for example, the Register method corresponds to register.html. One thing to note here is that Revel is looking through reflection to find the caller of the Controller.render method, and only looks up a layer.

For example, the following code is not working.

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 logic to handle registration for Postregister.

First, verify the validity of the parameters.

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 too much explanation, only one line

C.flashparams ()

It is the role of the form submitted by the parameters are stored in Flash, remember just the $field. Flash?

Now go play the registration page, fill in some wrong values to see the reaction, well, you should soon find that the error message although it has been shown, but unfortunately it is in English, modify it.

Func (c *account) postregister (user *models. Mockuser) Revel. Result {
C.validation.email (user. Email). Message ("Invalid e-mail format")
c.validation.required (user. Nickname). Message ("User nickname cannot be empty")
c.validation.required (user. Password). Message ("Password cannot be empty")
c.validation.required (user. ConfirmPassword = = user. Password). Message ("The password for two times entered is inconsistent")

If C.validation.haserrors () {
C.flashparams ()
Return C.redirect ((*account). Register)
}

Return C.render ()
}

Validation provides several commonly used verification methods, you can see for yourself, it should be easy to understand.

Continue, when all parameter checks pass, the DAL is called. The RegisterUser method stores user information in a database.

Func (c *account) postregister (user *models. Mockuser) Revel. Result {
C.validation.email (user. Email). Message ("Invalid e-mail format")
c.validation.required (user. Nickname). Message ("User nickname cannot be empty")
c.validation.required (user. Password). Message ("Password cannot be empty")
c.validation.required (user. ConfirmPassword = = user. Password). Message ("The password for two times entered is 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 a method registersuccessful to show that the registration was successful, so don't forget to add something to routes and view.

At this point, the user registration is complete. Do not know that you have noticed, even if you modify the go code, still do not need to restart Revel, directly refresh the browser page will find that the new code has been automatically compiled and enabled.

This is the meaning of the existence of Revel.exe, which monitors the file modifications of the entire project and then compiles and runs automatically. Development feels as comfortable as using Python and Ruby.

Today has mentioned a lot of revel knowledge points, hope to be useful to everyone, welcome any questions!

Finally, our pioneering products are completely written in Revel, which is a well-tested framework.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.