github.com/leowmjw/otto@v0.2.1-0.20160126165905-6400716cf085/rpc/serve.go (about)

     1  package rpc
     2  
     3  import (
     4  	"io"
     5  	"log"
     6  )
     7  
     8  // serveSingleCopy is a helper that creates a side-channel on our yamux
     9  // connection to send a stream of raw data.
    10  //
    11  // It is very important to wait for this to complete by listening on the
    12  // doneCh that is sent in so data isn't corrupted.
    13  func serveSingleCopy(
    14  	name string,
    15  	mux *muxBroker,
    16  	doneCh chan<- struct{},
    17  	id uint32, dst io.Writer, src io.Reader) {
    18  	defer close(doneCh)
    19  
    20  	conn, err := mux.Accept(id)
    21  	if err != nil {
    22  		log.Printf("[ERR] '%s' accept error: %s", name, err)
    23  		return
    24  	}
    25  
    26  	// Be sure to close the connection after we're done copying so
    27  	// that an EOF will successfully be sent to the remote side
    28  	defer conn.Close()
    29  
    30  	// The connection is the destination/source that is nil
    31  	if dst == nil {
    32  		dst = conn
    33  	} else {
    34  		src = conn
    35  	}
    36  
    37  	written, err := io.Copy(dst, src)
    38  	log.Printf("[INFO] %d bytes written for '%s'", written, name)
    39  	if err != nil {
    40  		log.Printf("[ERR] '%s' copy error: %s", name, err)
    41  	}
    42  }