Canceling an io.Copy operation in Go when a context expires is not straightforward because io.Copy itself does not directly support contexts. It is a blocking function that copies data from a source (io.Reader) to a destination (io.Writer) until there's no more data or an error occurs. To achieve cancellation, you need to:
Run io.Copy in a separate goroutine.
Use the context to detect cancellation and interrupt the underlying I/O operations (e.g., by closing the reader or writer if possible).
Handle the error propagation from the canceled operation.
This approach works best if the source or destination supports interruption, such as a network connection that can be closed. If you're dealing with something like a file (e.g., *os.File), cancellation might not be possible midway, as file I/O is typically uninterruptible without external means.
Step-by-Step Solution
Here's how you can implement this:
1. Understand the Limitations
io.Copy will only stop early if the reader returns an error (e.g., EOF or a network error).
If your reader is a network connection (e.g., *net.TCPConn), you can close it to trigger an error in io.Copy.
If your reader is not cancellable (e.g., a plain file), io.Copy will run to completion, and you can't truly cancel it from within Go without killing the process.
2. Basic Code Example
Use a goroutine to run io.Copy and monitor the context in the main goroutine. When the context is canceled, attempt to close or interrupt the reader.
go
package main
import (
"context"
"io"
"log"
"net" // Assuming a network reader for cancellability
"time"
)
func main() {
// Create a context with a timeout (e.g., 5 seconds)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Example: Source is a network connection (e.g., from net.Dial)
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close() // Ensure it's closed at the end
// Destination can be any io.Writer, e.g., a file or buffer
dst := []byte{} // Or use bytes.Buffer for testing
err = copyWithContext(ctx, dst, conn)
if err != nil {
if err == context.Canceled || err == context.DeadlineExceeded {
log.Println("Copy canceled due to context expiration:", err)
} else {
log.Println("Copy error:", err)
}
}
}
func copyWithContext(ctx context.Context, dst io.Writer, src io.Reader) error {
errChan := make(chan error, 1) // Buffered channel to avoid goroutine leak
go func() {
_, err := io.Copy(dst, src)
errChan <- err // Send the result when io.Copy finishes
}()
select {
case <-ctx.Done():
// Context is canceled; try to interrupt the reader
if closer, ok := src.(io.Closer); ok {
if err := closer.Close(); err != nil {
log.Println("Error closing source:", err)
}
}
return ctx.Err() // Return the context error
case err := <-errChan:
return err // io.Copy finished normally
}
}
Explanation:
Goroutine for io.Copy: We run io.Copy in a background goroutine so it doesn't block the main goroutine from checking the context.
Select on Context: In the main goroutine, we use a select statement to wait for either the context to be done or the io.Copy operation to complete.
Interrupting the Reader: If the context expires, we check if the reader implements io.Closer (e.g., *net.TCPConn). If it does, we close it, which should cause io.Copy to return an error (e.g., "use of closed network connection").
Error Handling: The error from io.Copy is sent via a channel. If the context cancels first, we return the context's error.
3. Key Considerations
Cancellable Readers: This works well for readers like:
Network connections (*net.TCPConn, *net.UDPConn), where closing the connection interrupts the read.
HTTP response bodies (*http.Response.Body), which can be closed.
Any custom reader that checks the context internally.
Non-Cancellable Readers: For readers like *os.File, closing the file might not interrupt an ongoing read (it could lead to an error on the next read, but not immediately). In such cases:
You might need to accept that cancellation isn't possible and let the operation finish.
Alternatively, read from the file in smaller chunks and check the context manually (see below).
Custom Context-Aware Reader: If your reader doesn't support cancellation, you can wrap it in a custom reader that checks the context:
This only works if the underlying reader supports short reads or if you handle it in a loop, as io.Copy doesn't check the context itself.
Potential Issues:
Race Conditions: Closing the reader while io.Copy is reading could lead to panics or unexpected errors. Always check if the reader is closable.
Resource Leaks: Ensure the goroutine doesn't leak by using a buffered channel or waiting for it to finish.
Performance: Checking the context frequently (e.g., in a custom reader) adds overhead.
4. Alternative Approaches
For HTTP Requests: If you're copying from an HTTP response body, use http.Client with a context:
go
client := &http.Client{}
req, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(dst, resp.Body) // This will be canceled if ctx is done
The http.Client handles cancellation for you.
Chunked Reading: If you need more control, manually read from the source in a loop and check the context:
go
func copyWithContextLoop(ctx context.Context, dst io.Writer, src io.Reader) error {
buf := make([]byte, 32*1024) // 32 KB buffer
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
n, err := src.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n > 0 {
_, writeErr := dst.Write(buf[:n])
if writeErr != nil {
return writeErr
}
}
if err == io.EOF {
return nil // Done reading
}
}
}
}
This avoids io.Copy altogether and checks the context on each read.
In summary, canceling io.Copy requires integrating it with a context by running it in a goroutine and interrupting the underlying resources. If your I/O operations aren't cancellable, you may need to redesign your approach or accept that cancellation isn't fully possible. Always test with your specific use case to ensure it behaves as expected.