Cookie 在 Gin 中,使用 Cookie 涉及到两个方法,Context.Cookie() 和 Context.SetCookie(): 1func SetCookie(c *gin.Context) { 2 // 设置 Cookie 3 c.SetCookie("gin-cookie", "test", 3600, "/", "localhost", false, false) 4 c.JSON(http.StatusOK, gin.H{ 5 "code": http.StatusOK, 6 "data": value, 7 }) 8} 9func GetCookie(c *gin.Context) { 10 // 获取...
Gin 中间件的配置方式有许多种,大致为: 在 Handle()、Any()、Match()、GET() 等基本路由方法中配置 HandlerFunc。 在 RouterGroup 的 Group() 方法中配置 HandlerFunc。 使用 Use() 方法配置 HandlerFunc。 特定请求的中间件 为特定请求配置中间件,可以直接在请求路由的 HandlerFunc 参数中配置。例如: controllers/user: 1type userController struct{} 2 3var UserController userController 4 5func (userController)...
Gin 中许多类型都可以认为它是一个路由(IRoutes)类型,这包括了 RouterGroup、Engine等。并且 IRoutes 接口中定义的方法都会有一个 IRoutes 类型的返回值,使得 Gin Routers 可以支持链式调用,让代码更加简洁。 路由分组 RouterGroup 是一种路由组对象(Engine 继承自 RouterGroup,所以也可以认为是一个路由组)。通过 Group() 方法可以创建一个新的 RouterGroup。Group() 方法的定义如下: 1func (group *RouterGroup) Group(relativePath string, handlers...
Gin 请求在 Gin 介绍 中做了简单的介绍。 Gin 请求与 RouterGroup 和 IRoutes 息息相关。IRoutes是一个接口类型,它定义了一系列用于配置路由处理的方法: 1type IRoutes interface { 2 // 用于配置路由中间件 3 Use(...HandlerFunc) IRoutes 4 5 // 路由处理方法 6 Handle(string, string, ...HandlerFunc) IRoutes 7 Any(string, ...HandlerFunc) IRoutes 8 GET(string, ...HandlerFunc) IRoutes 9 POST(string,...
Gin 支持各种响应数据类型:JSON、XML、HTML、YAML、Text 等等。响应数据需要使用到 gin.Context 类型。gin.Context 类型的作用有: 获取请求数据,包括请求头、Query 参数、Form 数据、Path 参数、请求体等。 响应管理,包括设置 HTTP 状态码、编写响应体、设置响应头等。 中间件支持。Context 可以携带当前处理函数的信息传递到下一个处理函数,直到达到最终的处理函数。在中间件中可以使用 Context 读取、修改 Context 的内容或终止请求处理流程。 Cookie 操作。 读写请求和响应体的原始字节流,以此来处理自定义协议或二进制数据传输。 错误处理。可以记录错误并中断...
Gin 是一个用 Golang 编写的 Web 框架。具有速度快、内存占用小等特点。 使用 Gin 下载并安装 Gin: 1$ go get -u github.com/gin-gonic/gin 引入 Gin: 1import "github.com/gin-gonic/gin" 如果需要使用诸如 http.StatusOK 之类的 HTTP 状态码常量,可以引入 net/http 包: 1import "net/http" 开始使用 Gin。 main.go: 1package main 2 3import "github.com/gin-gonic/gin" 4 5func main() { 6 // 获取...