跳转到内容

路由

Gin 提供了基于 httprouter 构建的强大路由系统,用于高性能的 URL 匹配。在底层,httprouter 使用基数树(也称为压缩字典树)来存储和查找路由,这意味着路由匹配非常快速,每次查找零内存分配。这使得 Gin 成为最快的 Go Web 框架之一。

通过在引擎(或路由组)上调用 HTTP 方法并提供 URL 模式和一个或多个处理函数来注册路由:

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/hello", func(c *gin.Context) {
c.String(http.StatusOK, "Hello, World!")
})
router.POST("/users", func(c *gin.Context) {
name := c.PostForm("name")
c.JSON(http.StatusCreated, gin.H{"user": name})
})
router.Run(":8080")
}

本节内容

以下页面详细介绍了每个路由主题: