Gin框架与《Web Development with Go》实践(二)

使用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
}
    原文作者:Cyberpunk_ZYM
    原文地址: https://segmentfault.com/a/1190000009664709
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞