热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Gin框架与《WebDevelopmentwithGo》实践(二)

使用gin改写“SectionBuildingRESTfulAPIs”第三方包需要提前准备的包有:“gopkg.ingin-gonicgin.v1”“gopkg.inmgo.v2”

使用gin改写“Section Building RESTful APIs”

第三方包

需要提前准备的包有:

  • “gopkg.in/gin-gonic/gin.v1”

  • “gopkg.in/mgo.v2”

  • “gopkg.in/mgo.v2/bson”

  • “github.com/dgrijalva/jwt-go”

  • “github.com/dgrijalva/jwt-go/request”

应用结构

见“实践(一)”

数据模型

数据模型对应mongodb中的文档类型。(此处无需用到gin)

import (
"gopkg.in/mgo.v2/bson"
"time"
)
type (
User struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
HashPassword []byte `json:"hashpassword,omitempty"`
}
Task struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
CreatedBy string `json:"createdby"`
Name string `json:"name"`
Description string `json:"description"`
CreatedOn time.Time `json:"createdon,omitempty"`
Due time.Time `json:"due,omitempty"`
Status string `json:"status,omitempty"`
Tags []string `json:"tags,omitempty"`
}
TaskNote struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
TaskId bson.ObjectId `json:"taskid"`
Description string `json:"description"`
CreatedOn time.Time `json:"createdon,omitempty"`
}
)

RESTful APIs的资源建模

以资源“task”为例,在RESTful APIs表中展示了其相应的资源路径和操作
《Gin框架与《Web Development with Go》实践(二)》

资源“task”的路由

src/taskmanager2/routers2/task.go

package routers2
import (
"gopkg.in/gin-gonic/gin.v1"
"taskmanager2/controllers2"
"taskmanager2/common2"
)
// SetTaskRoutes configures routes for task entity
func SetTaskRoutes(router *gin.Engine) *gin.Engine {
taR := router.Group("/tm2/tasks")
taR.Use(common2.Authorize())
{
taR.POST("", controllers2.CreateTask)
taR.PUT(":id", controllers2.UpdateTask)
taR.DELETE(":id", controllers2.DeleteTask)
taR.GET("", controllers2.GetTasks)
taR.GET("t/:id/", controllers2.GetTaskByID)
taR.GET("users/:email/", controllers2.GetTasksByUser)
}
return router
}

使用了gin的POST、PUT、DELETE和GET功能、router group功能,中间件功能,

注意:在GET路径”t/:id/”处,需要加上”t”以示区别;否则会报出路径冲突的错误。具体原因是与其源代码中借用的httprouter项目里的路径分析部分的代码有关;目前,我还未找到更合适的解决办法。

添加具体路径的中间件

“taR.Use()”中使用Use()函数添加中间件;还可以针对某一个具体的路径的具体方法添加中间件,具体用法请查阅官网文档。

RESTful API的初始化

src/taskmanager2/routers2/router.go
函数InitRoutes()需要使用gin进行改写。

package routers2
import (
"gopkg.in/gin-gonic/gin.v1"
)
func InitRoutes() *gin.Engine {
router := gin.Default()
// Routes for the User entity
router = SetUserRoutes(router)
// Routes for the Task entity
router = SetTaskRoutes(router)
// Routes for the TaskNote entity
router = SetNoteRoutes(router)
return router
}

推荐阅读
author-avatar
欣儿2502862161
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有