经过上一章节的介绍,搭建一个简单的 Gin web 项目非常容易,同时也引入了一些新的概念,比如说:路由 Router。
路由是一个非常重要的概念,所有的接口都要有路由来进行管理。
?请求方法
Gin 的路由支持 GET , POST , PUT , DELETE , PATCH , HEAD , OPTIONS 请求,同时还有一个 Any 函数,可以同时支持以上的所有请求。
将上一章节的代码添加其他请求方式的路由,并编写单元测试。
// 省略其他代码
// 添加 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)

本文详细介绍了Gin框架中的路由管理,包括请求方法、Handler处理器、路由参数的获取以及路由分组。通过实例展示了如何创建和组织路由,以及如何从路由中提取参数。此外,还探讨了如何利用路由分组提高代码的可维护性,并通过单元测试确保功能的正确性。
最低0.47元/天 解锁文章
374

被折叠的 条评论
为什么被折叠?



