一、环境安装
1、GO语言环境安装
【Golang】(二)Go语言环境安装_安装golang 环境-CSDN博客
2、Gin 介绍与环境搭建
二、路由
1、默认模式
main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 此 handler 将匹配 /user/john 但不会匹配 /user/ 或者 /user
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// 此 handler 将匹配 /user/john/ 和 /user/john/send
// 如果没有其他路由匹配 /user/john,它将重定向到 /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}
2、分组模式
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
server := gin.Default()
//默认模式
server.GET("/hello", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"message": "Hello World22",
})
})
//分组模式
user := server.Group("/user")
{
user.GET("/list", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"message": "user",
})
})
user.POST("/add/:id", func(context *gin.Context) {
//id := context.Param("id")
context.String(http.StatusOK, "id:id")
})
}
server.Run(":8080")
}
3、路由文件模式1
main.go
package main
import (
"gin01/router"
)
func main() {
server := router.Router()
server.Run(":8080")
}
router/user.go
package router
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Router() *gin.Engine {
r := gin.Default()
user := r.Group("/user")
{
user.GET("/list", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"message": "user",
})
})
user.POST("/add/:id", func(context *gin.Context) {
//id := context.Param("id")
context.String(http.StatusOK, "id:id")
})
}
return r
}
测试:
4、路由文件模式2
main.go
package main
import (
"gin01/router"
"github.com/gin-gonic/gin"
)
func main() {
// 创建服务
server := gin.Default()
// 路由设置
router.RouterUser(server)
router.RouterNews(server)
// 启动服务
server.Run(":8080")
}
router/user.go
package router
import (
"github.com/gin-gonic/gin"
"net/http"
)
func RouterUser(r *gin.Engine) {
user := r.Group("/user")
{
user.GET("/list", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"message": "user",
})
})
user.POST("/add/:id", func(context *gin.Context) {
//id := context.Param("id")
context.String(http.StatusOK, "id:id")
})
}
}
router/news.go
package router
import (
"github.com/gin-gonic/gin"
"net/http"
)
func RouterNews(r *gin.Engine) {
news := r.Group("/news")
{
news.GET("/list", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"message": "news",
})
})
news.POST("/add/:id", func(context *gin.Context) {
//id := context.Param("id")
context.String(http.StatusOK, "id:id")
})
}
}
推荐使用 路由文件模式2
测试
http://localhost:8080/news/list
http://localhost:8080/user/list