github.com/MetalBlockchain/metalgo@v1.11.9/x/sync/response_handler.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package sync 5 6 var _ ResponseHandler = (*responseHandler)(nil) 7 8 // Handles responses/failure notifications for a sent request. 9 // Exactly one of OnResponse or OnFailure is eventually called. 10 type ResponseHandler interface { 11 // Called when [response] is received. 12 OnResponse(response []byte) 13 // Called when the request failed or timed out. 14 OnFailure() 15 } 16 17 func newResponseHandler() *responseHandler { 18 return &responseHandler{responseChan: make(chan []byte)} 19 } 20 21 // Implements [ResponseHandler]. 22 // Used to wait for a response after making a synchronous request. 23 // responseChan contains response bytes if the request succeeded. 24 // responseChan is closed in either fail or success scenario. 25 type responseHandler struct { 26 // If [OnResponse] is called, the response bytes are sent on this channel. 27 // If [OnFailure] is called, the channel is closed without sending bytes. 28 responseChan chan []byte 29 } 30 31 // OnResponse passes the response bytes to the responseChan and closes the 32 // channel. 33 func (h *responseHandler) OnResponse(response []byte) { 34 h.responseChan <- response 35 close(h.responseChan) 36 } 37 38 // OnFailure closes the channel. 39 func (h *responseHandler) OnFailure() { 40 close(h.responseChan) 41 }