Golang
主页 > 脚本 > Golang >

Go中gin框架的*gin.Context参数常见实用方法

2024-07-14 | 佚名 | 点击:

梗概:

*gin.Context是处理HTTP请求的核心。ctx代表"context"(上下文),它包含了处理请求所需的所有信息和方法,例如请求数据、响应构建器、路由参数等。

基本的格式:

1

2

3

func SomeHandler(ctx *gin.Context) {

    // 使用ctx来处理请求和构建响应

}

常见的使用:

1. 读取查询参数

从请求中读取查询字符串参数。

1

2

3

4

5

6

func ReadQueryParams(ctx *gin.Context) {

    value := ctx.Query("someParam") // 获取查询参数

    ctx.JSON(http.StatusOK, gin.H{

        "someParam": value, // 回显参数

    })

}

2. 读取POST表单数据

对于POST请求中发送的表单数据的访问

1

2

3

4

5

6

func ReadPostForm(ctx *gin.Context) {

    value := ctx.PostForm("somePostParam") // 获取POST表单参数

    ctx.JSON(http.StatusOK, gin.H{

        "somePostParam": value,

    })

}

3. 读取JSON请求体

如果请求有JSON体,将其绑定到一个结构体。

1

2

3

4

5

6

7

8

9

10

11

12

13

type RequestBody struct {

    Message string `json:"message"`

}

func ReadJSONBody(ctx *gin.Context) {

    var body RequestBody

    if err := ctx.BindJSON(&body); err != nil {

        ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"}) // 绑定JSON失败

        return

    }

    ctx.JSON(http.StatusOK, gin.H{

        "message": body.Message,

    })

}

4. 写入JSON响应

向客户端写入JSON响应。

1

2

3

4

5

6

func WriteJSONResponse(ctx *gin.Context) {

    ctx.JSON(http.StatusOK, gin.H{

        "status": "success",

        "data": "some data",

    })

}

5. 流式响应

对于大型响应,您可以向客户端流式传输数据。

1

2

3

4

5

6

func StreamResponse(ctx *gin.Context) {

    for i := 0; i < 10; i++ {

        ctx.SSEvent("message", gin.H{"data": "Streaming " + strconv.Itoa(i)})

        time.Sleep(1 * time.Second)

    }

}

6. 访问路由参数

可以使用Param方法访问路由参数。

1

2

3

4

5

6

func RouteParameter(ctx *gin.Context) {

    productID := ctx.Param("id") // 获取路由参数

    ctx.JSON(http.StatusOK, gin.H{

        "product_id": productID,

    })

}

7. 设置Cookies

您可以设置和获取cookies。

1

2

3

4

5

6

7

func CookieExample(ctx *gin.Context) {

    ctx.SetCookie("username", "user1", 3600, "/", "localhost", false, true) // 设置cookie

    username := ctx.GetCookie("username") // 获取cookie

    ctx.JSON(http.StatusOK, gin.H{

        "cookie_username": username,

    })

}

8. 错误处理

您可以处理错误并返回适当的响应。

1

2

3

4

5

6

7

func ErrorHandling(ctx *gin.Context) {

    if someCondition {

        ctx.JSON(http.StatusBadRequest, gin.H{"error": "Bad request"}) // 发送错误响应

    } else {

        ctx.JSON(http.StatusOK, gin.H{"message": "Success"}) // 发送成功响应

    }

}

9. 文件上传

也支持处理文件上传。

1

2

3

4

5

6

7

8

9

func FileUpload(ctx *gin.Context) {

    file, err := ctx.FormFile("file") // 获取上传的文件

    if err != nil {

        ctx.JSON(http.StatusBadRequest, gin.H{"error": "Error uploading file"}) // 文件上传失败

        return

    }

    ctx.SaveUploadedFile(file, "path/to/save/"+file.Filename) // 保存文件

    ctx.JSON(http.StatusOK, gin.H{"message": "File uploaded successfully"}) // 文件上传成功

}

10. 使用中间件

*gin.Context经常在中间件中使用,以执行请求处理前后的动作。

1

2

3

4

5

6

7

8

9

10

11

12

13

func MyMiddleware(c *gin.Context) {

    c.Set("myKey", "myValue") // 在中间件中设置值

    c.Next()                   // 调用下一个中间件或处理器

}

func main() {

    router := gin.Default()

    router.Use(MyMiddleware) // 使用自定义中间件

    router.GET("/somepath", func(c *gin.Context) {

        value := c.Get("myKey") // 从中间件获取值

        c.JSON(http.StatusOK, gin.H{"myKey": value})

    })

    router.Run()

}

原文链接:
相关文章
最新更新