Skip to documentation
Documentation navigation

Documentation navigation

Documentation / guides

Close streams

Release stream resources with idempotent Close on every exit path.

developer

StreamReader.Close releases the underlying connection. It is safe to call more than once: the wrapped closer runs at most once and every call returns the first closer result.

API surface

func (r *StreamReader[T]) Close() error
reader, err := client.Stream(ctx, request)
if err != nil {
	return err
}
defer func() {
	if err := reader.Close(); err != nil {
		log.Printf("close stream: %v", err)
	}
}()

Close immediately after a successful Stream, before the loop starts. It should also be called after io.EOF; EOF records semantic completion but does not replace resource cleanup. A nil closer is a no-op. A nil receiver returns *StreamReaderError with Operation: StreamOperationClose.

Close is not serialized behind a blocking Next, which permits cancellation of an underlying read. The next/closer pair supplied by a codec must tolerate that concurrency.

Proof

Related: Streaming inference, Ownership and concurrency.

← back to documentation