gpt4 book ai didi

go - Go Gin中间件事件

转载 作者:行者123 更新时间:2023-12-01 22:17:06 25 4
gpt4 key购买 nike

我正在尝试使Gin服务器的中间件能够在单个请求中处理事件,因为我需要上下文中的IP地址之类的东西并且不传递整个上下文,而宁愿传递我的侦听器,这使我的方法不依赖于gin.Context
我设置了一个服务器

func main() {
router := gin.New()
router.Use(gin.Recovery())
api := router.Group("api", middleware())
{
api.GET("test/:id", endpoint)
}
router.Run("localhost:8080")
}
并制作了一个中间件
func middleware() gin.HandlerFunc {
return func(c *gin.Context) {
listener := make(chan int)
c.Set("EventListener", listener)
go func() {
select {
case <-listener:
fmt.Println("event called")
default:
fmt.Println("default")
}
}()
c.Next()
}
}
然后我得到了一个端点,在这里我得到了我的监听器,然后将其传递给我想要的任何函数
func endpoint(c *gin.Context) {
listener := c.MustGet("EventListener").(chan int)

id := c.Param("id")
idInt, err := strconv.ParseInt(id, 10, 64)
if err != nil {
fmt.Println(err)
return
}
doSomething(listener, int(idInt))
}
doSomething函数显示以后没有使用上下文
func doSomething(listener chan int, id int) {
if id == 1 {
fmt.Println("ERROR: cause event and exit")
listener <- int(id)
return
}
if id == 2 {
fmt.Println("WARN: cause event but continue")
listener <- int(id)
}
fmt.Println("OK: everything is fine")
}
现在它的工作方式是:
当您调用 GET http://localhost:8080/api/test/1时,它将触发事件并退出
当您调用 GET http://localhost:8080/api/test/2时,它将触发事件并继续工作
当您调用 GET http://localhost:8080/api/test/3时,它不会触发事件,因为一切正常。
因此,一切正常,但仅针对请求中的一个事件。您不能再调用另一个,因为 select已经通过,所以我的问题是如何修复它并允许多次触发事件。
我知道我可以做到
for {
select {
case <-listener:
fmt.Println("event called")
}
}
但是此循环的停止条件是什么?
我知道有些像 c.Done()的东西是 chan,但不知道如何在我的情况下使用它,因为我可以使它像
for {
select {
case <-listener:
fmt.Println("event called")
case <-c.Done():
return
}
}
但是如何传递那个 c.Done()?此 goroutine不会停止。

最佳答案

我发现还有c.Request.Context().Done()现在可以正常工作,可以停止goroutine并允许处理多个事件

go func() {
for {
select {
case <-listener:
fmt.Println("event called")
case <-c.Request.Context().Done():
return
}
}
}()

关于go - Go Gin中间件事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58916195/

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