gpt4 book ai didi

go - 有没有办法关闭 golang/gin 中的客户端请求?

转载 作者:IT王子 更新时间:2023-10-29 01:59:18 34 4
gpt4 key购买 nike

使用 gin框架。

有没有办法通知客户端关闭请求连接,然后服务器处理程序可以在不让客户端等待连接的情况下执行任何后台作业?

func Test(c *gin.Context) {
c.String(200, "ok")
// close client request, then do some jobs, for example sync data with remote server.
//
}

最佳答案

是的,你可以做到。通过简单地从处理程序返回。而你想做的后台工作,你应该把它放在一个新的 goroutine 上。

请注意,连接和/或请求可能会放回池中,但这无关紧要,客户端将看到服务请求已结束。你实现了你想要的。

像这样:

func Test(c *gin.Context) {
c.String(200, "ok")
// By returning from this function, response will be sent to the client
// and the connection to the client will be closed

// Started goroutine will live on, of course:
go func() {
// This function will continue to execute...
}()
}

另见:Goroutine execution inside an http handler

关于go - 有没有办法关闭 golang/gin 中的客户端请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470792/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com