"Go Web Development Revel+mgo" The 4th chapter realizes the comment function

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

Sorry, ladies and gentlemen, before starting this chapter, please come first, the 5th chapter of the whole project CSS copy out, this chapter forgot to add, originally wanted to add in the back, but found that the content of the page too much


1. Design Review page

The previous chapter we did a simple blog and display function, here have to say, first of all, our blog can not add image links such things, do not support markdown grammar. Bo Master is lazy, try to find a few plug-ins found dissatisfied after not want to try (in fact, can find GitHub writing Wiki editor is what I want, who knows to tell me OH), you can try to find some of their own favorite editor (although the Revel Chinese community that has been very good, But the pop-up box style is not like, Golang Community editor is also very strong, but also not my favorite style, your sister Ah, so picky .... ), in short, we can refer to, like to use.
Create a new bloginfor.html content below Views/app:
{{set.} "title" "Bloginfor-gblog"}}{{set. "Home" "Active"}}{{template "header.html".}} <div class= "Content" > <div class= "infor-content" > <div class= "Infor-header" > &LT;H3&G T title

Add our handling methods in App/controllers/app.go:
Func (c App) bloginfor () Revel. Result {return C.render ()}

Add a path to the conf/routes:
GET     /bloginfor               app.bloginfor

OK in the address with http://localhost:9000/bloginfor access to see, the effect:

Let's implement it.

2. Implement Comment function

First look at the link content of the title in our index.html:
/bloginfor/{{$blog. id.hex}}/{{$blog. READCNT}}

Well, yes, we pass the blog ID and read the number of times, why to pass the number of reading, because from this link in the time we want to read the number of times plus 1, but if we do not pass, then to the detailed page should be directly in the DB data added, so there is a problem, I am in the detailed page has been pressing F5 refresh, found that the number of reading quickly increased, which makes me very helpless, how to do it, the number of reading is also passed over, at least the original step to increase the 2 steps, a little relief, but still do not know the best way ah, the best way is that we get, request the user's IP, This IP can only be added once, which is something.
Okay, let's change the configuration of the path conf/routes:
GET     /bloginfor/:id/:rcnt                    app.bloginfor

Add two parameters to the Bloginfor method inside the App/controllers/app.go:
Func (c App) bloginfor (id string,rcnt int) Revel. Result {return C.render ()}

OK, this time we click on the title of our blog to see if it is normal to enter the detailed page.
My side is OK, we go down, first app/controllers/app.go the Bloginfor method, modified as follows:
Func (c App) bloginfor (id string,rcnt int) Revel. Result {DAO, err: = models. Newdao () if err! = Nil {c.response.status = 500return c.rendererror (err)}defer DAO. Close () Blog: = Dao. Findblogbyid (ID) if (blog. readcnt==rcnt) {Blog. readcnt = Rcnt+1dao. Updateblogbyid (Id,blog)}return C.render (blog,rcnt)}

We go to find this blog, and read the number of times to update, look at the inside of the judgment, we are the number of reading and DB in comparison, only the equivalent of the situation to update, it does add 2 steps. However, if you have time, you can also use another method, is to read the number of encryption (reversible encryption), decrypted and then compared with the DB, so that the user wants to modify the encrypted thing is not an easy event.
Then our model also has a corresponding method, open App/models/blog.go, add method:
Func (DAO *dao) Findblogbyid (ID string) *blog{blogcollection: = Dao.session.DB (DbName). C (blogcollection) Blog: = new (blog) Query: = Blogcollection.find (Bson. m{"id": Bson. Objectidhex (ID)}) query. One (blog) return Blog}func (DAO *dao) Updateblogbyid (id string,blog *blog) {blogcollection: = Dao.session.DB (DbName). C (blogcollection) Err: = Blogcollection.update (Bson. m{"id": Bson. Objectidhex (ID)}, blog) if Err!=nil{revel. WARN. Printf ("Unable to update blog:%v error%v", blog, Err)}

One is to find, one is to update, nothing to say.
Open Views/app/bloginfor.html modified to:
{{set.} "title" "Bloginfor-gblog"}}{{set. "Home" "Active"}}{{template "header.html".}}          <div class= "Content" > {{if. Blog}} <div class= "Infor-content" > <div class= "Infor-header" > 

The blog information is displayed. OK, click to see the effect:



OK, let's make a comment. Create Comment.go content under App/models:
Package Modelsimport ("Github.com/revel/revel" "Labix.org/v2/mgo/bson" "Time") type Comment struct{blogid Bson. ObjectId Email stringcdate time. Timecontent String}func (Comment *comment) Validate (v *revel. Validation) {V.check (comment. Email,revel. Required{},revel. MAXSIZE{50},) V.email (comment. Email) V.check (comment. Content,revel. Required{},revel. Minsize{1},revel. maxsize{1000},)}func (DAO *dao) insertcomment (comment *comment) error {commcollection: = Dao.session.DB (DbName). C (commentcollection)//set the timecomment. CDate = time. Now (); Err: = Commcollection.insert (comment) if err! = Nil {Revel. WARN. Printf ("Unable to save Comment:%v error%v", Comment, Err)}return Err}func (dao *dao) findcommentsbyblogid (ID bson. OBJECTID) []comment{commcollection: = Dao.session.DB (DbName). C (commentcollection) Comms: = []comment{}query: = Commcollection.find (Bson. m{"blogID": ID}). Sort ("CDate") query. All (&AMP;COMMS) return comms}

Very similar to our blog.go, no need to explain. With DAO, let's Make the logic, or do the function of submitting comments first, look at our bloginfo.html page. The final form form, the contents of which are similar to the one we talked about in the previous chapter.
Under App/controllers new Wcomment.go, why start with W, write, Content:
Package Controllersimport ("Github.com/revel/revel" "Gblog/app/models" "strings") type wcomment struct {app}func (c Wcomment) docomment (id string,rcnt int,comment *models. Comment) Revel. Result {if Len (id) ==0{return c.redirect (app.index)}dao, err: = models. Newdao () if err! = Nil {c.response.status = 500return c.redirect (app.index)}defer DAO. Close () Blog: = Dao. Findblogbyid (ID) if Blog==nil {return c.redirect (App.index)}comment. BlogId = blog. Idcomment.content = strings. Trimspace (comment. Content) comment. Email = strings. Trimspace (comment. Email) comment. Validate (c.validation) if C.validation.haserrors () {c.validation.keep () C.flashparams () c.flash.error ("Errs:The Email and the content should not being null,or the maxsize of email is 50. ") Return C.redirect ("/bloginfor/%s/%d", id,rcnt)}err = DAO. Insertcomment (comment) if err!=nil {c.response.status = 500return c.rendererror (err)}blog. Commentcnt++dao. Updateblogbyid (Id,blog) return C.redirect ("/bloginfor/%s/%d", id,rcnt)}

Look at the logic inside, we first to find out, there is no this blog object, no, then directly return to the index page, and then the comment check, and finally our blog comment number plus 1. The last C. Redirect ("/bloginfor/%s/%d", id,rcnt) is to get it back to the Infor page again.
OK, add our path, Conf/routes:
POST    /docomment                 wcomment.docomment

You can try to submit it successfully. Although there is still no result to see. Here's our comment, in App/controllers/app.go's Bloginfor method, add the following code before return:
Comments: = DAO. Findcommentsbyblogid (blog. ID), If Len (comments) ==0&&blog.commentcnt!=0{blog.commentcnt=0;dao. Updateblogbyid (id,blog)}else If Len (comments)!=blog.commentcnt{blog.commentcnt=len (comments);d AO. Updateblogbyid (Id,blog)}

The final return is modified to:
Return C.render (blog,rcnt,comments)

Open the views/app/bloginfor.html and put the blocks in it:
<div class= "Comments" >        <span> reply </span>        


Modified to:
{{If. Comments}}    <div class= "Comments" >        <span> reply </span>        

Ah yo, good oh, basically finished, why say basically, because you now refresh the page should be wrong, see? The above code:
{{pls $index 1}}
This is used to show the floor of the thing, this is our custom template, here we have to thank the Revel Chinese community Kevin, if we use $index directly, it's starting from 0, this ...
OK, open our app/init.go, saying there are a lot of things I do not know, I will not tell you, Func init () added:
Revel. templatefuncs["pls"] = func (A, b int) int {return a + B}

is to define a simple template method.
Are you ready? Guys, hurry up and try the long-awaited comment function.


Nice Have you succeeded?
Source Address:Https://github.com/joveth/GBlog

AC qq:158325682


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.