【Go web开发之revel+mgo】第8章 实现Email墙
演示地址 http://gblog-revel.herokuapp.com/
1.设计Email墙页面
{{set . "title" "Email list - GBlog"}} {{set . "ema" "active" }} {{template "header.html" .}} <div class="content"> <div class="email-nav" > <span class="email-tag"> <img src="http://www.gravatar.com/avatar/8b801bb6de1a876f7df749cedb8994a6?s=64" style="border-radius:32px"/> <span>jov123@163.com</span> </span> </div> </div> </div> </body> </html>其中,img的url里面那一串,是博主自己的email加密后的串。后面会教大家怎么做这个东西。
在controllers/app.go加入方法:
func (c App) Emails() revel.Result { return c.Render() }
GET /email App.Emails
ok,看看效果:
2.实现email墙
package models import ( "github.com/revel/revel" "labix.org/v2/mgo/bson" "time" "crypto/md5" "io" "fmt" ) type EmailObj struct{ Email string ImgUrl string CDate time.Time } func (dao *Dao) InsertEmail(emailObj *EmailObj) error { emailCollection := dao.session.DB(DbName).C(EmailCollection) emailObj.CDate = time.Now(); h := md5.New() io.WriteString(h, emailObj.Email) emailObj.ImgUrl = fmt.Sprintf("%x", h.Sum(nil)) fmt.Println(emailObj) _,err := emailCollection.Upsert(bson.M{"email": emailObj.Email}, emailObj) if err != nil { revel.WARN.Printf("Unable to save EmailObj: %v error %v", emailObj, err) } return err } func (dao *Dao) FindAllEmails() []EmailObj{ emailCollection := dao.session.DB(DbName).C(EmailCollection) emails := []EmailObj{} query := emailCollection.Find(bson.M{}).Sort("-cdate") query.All(&emails) return emails }
看一下,insert方法,里面我们为url做了md5加密,这个是go自带的东西,只需要引入即可,我这来简单的使用了一下。另外,我们的mgo的Upsert方法,以email为主,如果有这个email,我们就只做更新,如果没人,就做插入,这个策略很不错。
func (c App) Emails() revel.Result { dao, err := models.NewDao() if err != nil { c.Response.Status = 500 return c.RenderError(err) } defer dao.Close() emails :=dao.FindAllEmails(); return c.Render(emails) }
将views/App/Emails.html最后修改为:
{{set . "title" "Email list - GBlog"}} {{set . "ema" "active" }} {{template "header.html" .}} <div class="content"> <div class="email-nav" > {{if .emails}} {{range $email:= .emails}} <span class="email-tag"> <img src="http://www.gravatar.com/avatar/{{$email.ImgUrl}}?s=64" style="border-radius:32px"/> <span title="last update at:{{$email.CDate.Format "2006-01-02 15:04"}}">{{$email.Email}}</span> </span> {{end}} {{end}} </div> </div> </div> </body> </html>
恩,做完了吗?
newEmail := new(models.EmailObj); newEmail.Email = blog.Email; dao.InsertEmail(newEmail);
同样在wcomment.go的Docomment方法中,return之前添加内容:
newEmail := new(models.EmailObj); newEmail.Email = comment.Email; dao.InsertEmail(newEmail);
newEmail := new(models.EmailObj); newEmail.Email = message.Email; dao.InsertEmail(newEmail);
ok,这样,不管是发blog还是评论,还是留言都会为我们增加email。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。