GO語言Gin包(路由 router)


GO語言Gin包

Gin 是一個用 Golang 寫的 http web 框架。

路由是一個非常重要的概念,所有的接口都要有路由來進行管理。

  • Gin 的路由支持 GET , POST , PUT , DELETE , PATCH , HEAD , OPTIONS 請求,同時還有一個 Any 函數,可以同時支持以上的所有請求。

  • eg:
// 省略其他代碼
// 添加 Get 請求路由
router.GET("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin get method")
})
// 添加 Post 請求路由
router.POST("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin post method")
})
// 添加 Put 請求路由 
router.PUT("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin put method")
})
// 添加 Delete 請求路由
router.DELETE("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin delete method")
})
// 添加 Patch 請求路由
router.PATCH("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin patch method")
})
// 添加 Head 請求路由
router.HEAD("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin head method")
})
// 添加 Options 請求路由
router.OPTIONS("/", func(context *gin.Context) {
    context.String(http.StatusOK, "hello gin options method")
})
// 省略其他代碼

路由分組

  • 通過 router.Group 返回一個新的分組路由,通過新的分組路由把之前的路由進行簡單的修改。當然分組里面仍舊可以嵌套分組。
  • eg:
index := router.Group("/")
{
    // 添加 Get 請求路由
    index.GET("", retHelloGinAndMethod)
    // 添加 Post 請求路由
    index.POST("", retHelloGinAndMethod)
    // 添加 Put 請求路由
    index.PUT("", retHelloGinAndMethod)
    // 添加 Delete 請求路由
    index.DELETE("", retHelloGinAndMethod)
    // 添加 Patch 請求路由
    index.PATCH("", retHelloGinAndMethod)
    // 添加 Head 請求路由
    index.HEAD("", retHelloGinAndMethod)
    // 添加 Options 請求路由
    index.OPTIONS("", retHelloGinAndMethod)
}

  • Any 函數可以通過任何請求,此時我們就可以把 index 里面所有的請求替換為 Any
  • eg:
index := router.Group("/")
{
    index.Any("", retHelloGinAndMethod)
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM