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