生命不止,继续go go go !!!
之前介绍过golang中restful api的博客,是使用redis作为持久化,httprouter作为框架:
Go实战–通过httprouter和redis框架搭建restful api服务(github.com/julienschmidt/httprouter)
今天,继续echo框架,这次加入mongodb作为持久化存储,使用jwt进行验证,来搭建一套rest api,类似Twitter。
其中,很多知识点之前都有介绍过:
关于golang中使用mongodb科技参考:
Go实战–golang使用ssl连接MongoDB(mgo)
Go实战–golang中使用MongoDB(mgo)
关于golang中的使用jwt(JSON Web Token):
Go实战–golang中使用JWT(JSON Web Token)
代码结构:
./model post.go user.go./handler handler.go post.go user.gomain.go12345678
model
这里没有什么好说的,就是建立model,需要注意的就是golang中struct中的标签。
一个用户user,一个邮箱post。
user.go
package modelimport ( "gopkg.in/mgo.v2/bson")type ( User struct { ID bson.ObjectId `json:"id" bson:"_id,omitempty"` Email string `json:"email" bson:"email"` Password string `json:"password,omitempty" bson:"password"` Token string `json:"token,omitempty" bson:"-"` Followers []string `json:"followers,omitempty" bson:"followers,omitempty"` })123456789101112131415
post.go
package modelimport ( "gopkg.in/mgo.v2/bson")type ( Post struct { ID bson.ObjectId `json:"id" bson:"_id,omitempty"` To string `json:"to" bson:"to"` From string `json:"from" bson:"from"` Message string `json:"message" bson:"message"` })123456789101112131415
handler
handler.go
handler中提出出来的公共部分。
package handlerimport ( "gopkg.in/mgo.v2")type ( Handler struct { DB *mgo.Session })const ( // Key (Should come from somewhere else). Key = "secret")1234567891011121314151617
post.go
post中加入两个功能,一个创建post,一个拉取post。
关于”net/http”可以参考:
Go语言学习之net/http包(The way to go)
关于”strconv”可以参考:
Go语言学习之strconv包(The way to go)
package handlerimport ( "go_echo_examples/twitter/model" "net/http" "strconv" "github.com/labstack/echo" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson")func (h *Handler) CreatePost(c echo.Context) (err er