顶级目录 gin
1.bootstrap/route.go 路由 在这里注册
package bootstrap
import (
"gin/routes"
"github.com/gin-gonic/gin"
)
func SetupRoute(r *gin.Engine) {
routes.RegisterAPIRoutes(r)
}
2.routes/route.go 具体路由
package routes
import (
"fmt"
"github.com/gin-gonic/gin"
)
func RegisterAPIRoutes(r *gin.Engine) {
v1 := r.Group("/v1")
v1.GET("hello", func(ctx *gin.Context) {
fmt.Println("helloword")
})
}
3.将 注册的路由 引入到 main.go
package main
import (
"fmt"
"gin/bootstrap"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
//数据库驱动
//bootstrap.SetupDB()
//路由驱动
bootstrap.SetupRoute(r)
// 运行服务
err := r.Run(":8080")
if err != nil {
fmt.Println(err.Error())
}
}
go run main.go
curl 127.0.0.1:8080/v1/hello
结果:helloword

本文介绍了 Gin 框架的路由注册过程,从 `bootstrap/route.go` 中的初始化,到 `routes/route.go` 的具体路由设置,再到 `main.go` 中的启动和运行。通过示例代码展示了如何在 Gin 中注册并运行 `/v1/hello` 路由,当访问该路径时,会输出 'helloword'。
748

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



