-
Notifications
You must be signed in to change notification settings - Fork 658
/
response_handler.go
42 lines (35 loc) · 1.31 KB
/
response_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package sync
var _ ResponseHandler = (*responseHandler)(nil)
// Handles responses/failure notifications for a sent request.
// Exactly one of OnResponse or OnFailure is eventually called.
type ResponseHandler interface {
// Called when [response] is received.
OnResponse(response []byte)
// Called when the request failed or timed out.
OnFailure()
}
func newResponseHandler() *responseHandler {
return &responseHandler{responseChan: make(chan []byte)}
}
// Implements [ResponseHandler].
// Used to wait for a response after making a synchronous request.
// responseChan may contain response bytes if the original request has not failed.
// responseChan is closed in either fail or success scenario.
type responseHandler struct {
// If [OnResponse] is called, the response bytes are sent on this channel.
responseChan chan []byte
// Set to true in [OnFailure].
failed bool
}
// OnResponse passes the response bytes to the responseChan and closes the channel
func (h *responseHandler) OnResponse(response []byte) {
h.responseChan <- response
close(h.responseChan)
}
// OnFailure sets the failed flag to true and closes the channel
func (h *responseHandler) OnFailure() {
h.failed = true
close(h.responseChan)
}