gin.Context 提供的方法

24 min read

context 是 *gin.Context 类型的一个实例,它提供了许多功能,包括请求处理、响应处理和中间件管理等。以下是

// 获取请求参数
queryParam := context.Query("param")
pathParam := context.Param("param")
formValue := context.PostForm("param")
jsonValue := context.PostForm("param")

// 获取请求头信息
headerValue := context.GetHeader("header")

// 获取请求方法和路径
method := context.Request.Method
path := context.Request.URL.Path

// 设置响应状态码
context.Status(http.StatusOK)

// 设置响应头信息
context.Header("Content-Type", "application/json")

// 发送响应数据
context.String(http.StatusOK, "Hello, gin")
context.JSON(http.StatusOK, gin.H{"message": "Hello, gin"})
context.XML(http.StatusOK, gin.H{"message": "Hello, gin"})

// 使用中间件
engine.Use(middlewareFunction)

// 中止中间件链的执行
context.Abort()

// 传递数据给后续中间件或处理函数
context.Set("key", "value")
value, exists := context.Get("key")

context.Writer.Write([]byte("Hello, gin\n"))