提问人:mrasoolmirza 提问时间:11/17/2023 最后编辑:mrasoolmirza 更新时间:11/17/2023 访问量:35
客户端如何向 graphql 订阅服务器发送关闭信号?
How client sends close signal to graphql subscription server?
问:
我正在 graphql 服务器上工作,并且有一个订阅 API。这是我在 gqlgen 文档上找到的起始代码:
// CurrentTime is the resolver for the currentTime field.
func (r *subscriptionResolver) CurrentTime(ctx context.Context) (<-chan *model.Time, error) {
// First you'll need to `make()` your channel. Use your type here!
ch := make(chan *model.Time)
// You can (and probably should) handle your channels in a central place outside of `schema.resolvers.go`.
// For this example we'll simply use a Goroutine with a simple loop.
go func() {
// Handle deregistration of the channel here. Note the `defer`
defer close(ch)
for {
// In our example we'll send the current time every second.
time.Sleep(1 * time.Second)
fmt.Println("Tick")
// Prepare your object.
currentTime := time.Now()
t := &model.Time{
UnixTime: int(currentTime.Unix()),
TimeStamp: currentTime.Format(time.RFC3339),
}
// The subscription may have got closed due to the client disconnecting.
// Hence we do send in a select block with a check for context cancellation.
// This avoids goroutine getting blocked forever or panicking,
select {
case <-ctx.Done(): // This runs when context gets cancelled. Subscription closes.
fmt.Println("Subscription Closed")
// Handle deregistration of the channel here. `close(ch)`
return // Remember to return to end the routine.
case ch <- t: // This is the actual send.
// Our message went through, do nothing
}
}
}()
// We return the channel and no error.
return ch, nil
}
我想知道收到 ctx 后会发生什么。Done() 信号。客户端是否通过取消订阅或关闭订阅来发送此信号?或者它可以在一段时间后自动发生?(我的意思是设置一些空闲的超时参数。 另外,我想知道我这边(服务器端)的超时可以触发 Done() 信号吗?
答: 暂无答案
评论