1.设计Email墙页面
呀,什么是email墙啊,这,博主,随便扯了点东西把,不知到大家西部喜欢,先来做,后面看效果吧。
首先在views/App下新建Emails.html 内容:
{{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墙
首先在models下新建email.go 内容:
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,我们就只做更新,如果没人,就做插入,这个策略很不错。
好,在controllers/app.go的Emails方法里面添加:
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>
恩,做完了吗?
当然没有,我们这里做了数据的读取,却没有插入,怎么办呢,好,还记得我们controllers下的以w开头的类吗,这就是我们的入口。
首先在wblog.go的Putup方法中,return之前添加内容:
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。
来看看最后的效果:
nice,你做好了吗?