gin框架 路由
1. 什么是路由
路由(route)就是根据 HTTP 请求的 URL,设置由哪个函数来处理请求。路由是 Web 框架的核心功能。
路由通常这样实现:根据路由里的字符 “/”,把路由切分成多个字符串数组,然后构造成树状结构;寻址的时候,先把请求的 URL 按照 “/” 进行切分,然后遍历树进行寻址。
比如:定义了两个路由 /user/get,/user/delete,则会构造出拥有三个节点的路由树,根节点是 user,两个子节点分别是 get 和 delete。
2. gin 框架路由库
gin 框架中采用的路由库是基于 httprouter 开发的。
httprouter 项目地址:https://github.com/julienschmidt/httprouter。
3. gin 框架路由的语法
Gin 的路由支持 HTTP 的 GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS 方法的请求,同时还有一个 Any 函数,可以同时支持以上的所有请求。
Gin 的路由通常的使用方法如下:
// 获取默认的 gin Engine,Engine 中包含了所有路由处理的接口
engine := gin.Default()
// Get 请求路由
engine.GET("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin get method")
})
// Post 请求路由
engine.POST("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin post method")
})
// Put 请求路由
engine.PUT("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin put method")
})
// Delete 请求路由
engine.DELETE("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin delete method")
})
// Patch 请求路由
engine.PATCH("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin patch method")
})
// Head 请求路由
engine.HEAD("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin head method")
})
// Options 请求路由
engine.OPTIONS("/", func(context *gin.Context) {
context.String(http.StatusOK, "hello gin options method")
})
4. gin 框架路由的范例
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
engine := gin.Default()
// 下面是两条路由
engine.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "编程教程")
})
engine.GET("/hello", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})
// 监听端口默认为8080
engine.Run(":8080")
}
运行程序,然后打开浏览器,输入 http://localhost:8080/,可以看到浏览器输出:编程教程。然后输入 http://localhost:8080/hello,可以看到浏览器输出:Hello World。
下一章:gin框架 RESTful API
web 应用程序,一般分为前端和后端两个部分。前后端通常需要一种统一的通信机制,方便不同的前端设备与后端进行通信。这导致API构架的流行,甚至出现"API First"的设计思想。RESTful API是目前比较成熟的一套互联网应用程序的 API 设计理论。gin 框架支持 RESTful 风格的 API。
AI 中文社