httpseek

package module
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 8 Imported by: 7 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httpseek

Go Report Card GoDoc GitHub license

This is a simple HTTP seeker that can be used to seek through a file using HTTP range requests.

Usage

Seeker implements io.ReadSeekCloser on top of an HTTP endpoint:

req, _ := http.NewRequest(http.MethodGet, "https://example.com/large-file", nil)
rsc := httpseek.NewSeeker(context.Background(), http.DefaultTransport, req)
defer rsc.Close()

// Read/Seek like a local file; each jump is served by a Range request.
rsc.Seek(-16, io.SeekEnd)
io.ReadAll(rsc)

Also available: NewRangeSeeker (bounded range), NewSuffixSeeker (last N bytes), and NewSeekerWithHTTPClient (follows redirects via an *http.Client).

Seeking from io.SeekEnd learns an unknown size with a HEAD probe, falling back to a ranged request when HEAD is unsupported; Size() reports -1 while the total is still unknown.

The seek logic is protocol-agnostic: implement Opener (ranged opens plus a size probe) and wrap it with NewOpenSeeker / NewRangeOpenSeeker / NewSuffixOpenSeeker to get the same io.ReadSeekCloser over any resource.

NewMustReaderTransport wraps a http.RoundTripper so interrupted GET downloads are transparently resumed with Range requests:

client := &http.Client{
    Transport: httpseek.NewMustReaderTransport(http.DefaultTransport,
        httpseek.RetryWithBackoff(3, time.Second)),
}
resp, _ := client.Get("https://example.com/large-file")
defer resp.Body.Close()
// resp.Body retries and resumes on transient read errors.

Content consistency across reconnects is guarded with If-Range and ETag/Last-Modified validation; a changed file surfaces ErrContentChanged instead of mixed content.

MIT License

Licensed under the MIT License. See LICENSE for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCodeForByteRange is returned when the HTTP status code is not 206 for a byte range request.
	ErrCodeForByteRange = errors.New("expected HTTP 206 from byte range request")

	// ErrNoContentRange is returned when the Content-Range header is missing from a 206 response.
	ErrNoContentRange = errors.New("no Content-Range header found in HTTP 206 response")

	// ErrInvalidContentRange is returned when the Content-Range header cannot be parsed or does not match the requested range.
	ErrInvalidContentRange = errors.New("invalid Content-Range header")

	// ErrRangeNotSatisfiable is returned when the server responds with HTTP 416.
	ErrRangeNotSatisfiable = errors.New("requested range not satisfiable")

	// ErrContentChanged is returned when the content changed between requests:
	// a response validator mismatched, or a server honoring If-Range answered a
	// range request with a full response. Subsequent reads keep failing; create
	// a new Seeker to read the changed content.
	ErrContentChanged = errors.New("content changed during read")

	// ErrUnsupported indicates that the target response is not supported, such as for 30x or 401 responses.
	ErrUnsupported = errors.New("unsupported target response")

	// ErrSizeUnknown is returned by Seek with io.SeekEnd when the total size
	// of the resource cannot be determined.
	ErrSizeUnknown = errors.New("resource size unknown")
)

Functions

func NewMustReadSeekCloser added in v0.5.0

func NewMustReadSeekCloser(rsc io.ReadSeekCloser, offset int64, errorHandler func(int, error) error) io.ReadSeekCloser

NewMustReadSeekCloser returns a reader that will retry reading with partial byte ranges if the underlying reader returns an error.

func NewMustReadSeeker added in v0.5.0

func NewMustReadSeeker(rsc io.ReadSeeker, offset int64, errorHandler func(int, error) error) io.ReadSeeker

NewMustReadSeeker returns a reader that retries reading if the underlying reader returns an error. offset must be the current absolute position of rsc; it is used to restore the position before retrying. errorHandler receives the retry count and the error; returning a non-nil error stops retrying and is reported to the caller.

func NewMustReaderTransport

func NewMustReaderTransport(baseTransport http.RoundTripper, errorHandler func(*http.Request, int, error) error) http.RoundTripper

NewMustReaderTransport returns a transport that will retry reading with partial byte ranges if the underlying transport returns an error.

func RetryWithBackoff added in v0.7.0

func RetryWithBackoff(maxRetries int, base time.Duration) func(*http.Request, int, error) error

RetryWithBackoff returns an error handler for NewMustReaderTransport that retries up to maxRetries times with exponential backoff starting at base (no sleep if base <= 0).

Types

type HTTPClient added in v0.4.0

type HTTPClient interface {
	Do(r *http.Request) (*http.Response, error)
}

type OpenResult added in v0.7.0

type OpenResult struct {
	// Body streams the opened range; nil when the open failed.
	Body io.ReadCloser
	// Start and End are the resolved byte range; End is the inclusive
	// end byte, -1 for open-ended.
	Start, End int64
	// Size is the total size of the resource; -1 if unknown.
	Size int64
	// Validator identifies the content version; empty if none.
	Validator string
}

OpenResult is the outcome of an OpenRange call.

type OpenSeeker added in v0.7.0

type OpenSeeker struct {
	// contains filtered or unexported fields
}

OpenSeeker adapts an Opener into an io.ReadSeekCloser. It is not safe for concurrent use.

func NewOpenSeeker added in v0.7.0

func NewOpenSeeker(opener Opener) *OpenSeeker

NewOpenSeeker assembles an io.ReadSeekCloser on top of an Opener, reading the whole resource. A validator captured from the first open is passed to later opens so the Opener can detect content changes.

func NewRangeOpenSeeker added in v0.7.0

func NewRangeOpenSeeker(opener Opener, start, end int64) *OpenSeeker

NewRangeOpenSeeker assembles an io.ReadSeekCloser that reads a bounded byte range [start, end] of the resource. end is the inclusive end byte; -1 means open-ended (read to EOF). A negative start requests the suffix of length end, as in Opener.OpenRange.

func NewSuffixOpenSeeker added in v0.7.0

func NewSuffixOpenSeeker(opener Opener, suffixLen int64) *OpenSeeker

NewSuffixOpenSeeker assembles an io.ReadSeekCloser that reads the last suffixLen bytes of the resource. The actual byte range is resolved by the Opener on the first open.

func (*OpenSeeker) Close added in v0.7.0

func (s *OpenSeeker) Close() error

Close closes the OpenSeeker.

func (*OpenSeeker) OK added in v0.7.0

func (s *OpenSeeker) OK() bool

OK indicates whether the OpenSeeker is ready to be read.

func (*OpenSeeker) Offset added in v0.7.0

func (s *OpenSeeker) Offset() int64

Offset returns the current offset of the OpenSeeker.

func (*OpenSeeker) Read added in v0.7.0

func (s *OpenSeeker) Read(p []byte) (n int, err error)

func (*OpenSeeker) Seek added in v0.7.0

func (s *OpenSeeker) Seek(offset int64, whence int) (int64, error)

Seek sets the offset for the next Read to the specified offset. Seeking to a different offset clears the error classification cached from the last unsupported open; seeking to the current offset preserves it.

func (*OpenSeeker) Size added in v0.7.0

func (s *OpenSeeker) Size() int64

Size returns the last known total size of the resource; -1 if unknown.

type Opener added in v0.7.0

type Opener interface {
	// OpenRange opens the byte range [start, end] of the resource, where end
	// is the inclusive end byte and -1 means open-ended (read to EOF);
	// start 0 with end -1 opens the whole resource.
	// A negative start requests the suffix of length end; the resolved range
	// is reported back in the result.
	// Implementations report ErrRangeNotSatisfiable for a range beyond EOF and
	// ErrUnsupported for other unsupported opens; the result's Size stays
	// meaningful alongside these two errors, and its Validator alongside
	// ErrRangeNotSatisfiable.
	// A non-empty validator argument requires the content to still match it;
	// implementations report ErrContentChanged when it does not, or may just
	// report the current version in Validator for the caller to compare.
	OpenRange(validator string, start, end int64) (OpenResult, error)

	// Size reports the total size of the resource in the result; -1 if unknown.
	// The validator argument behaves as in OpenRange, and the result's
	// Validator reports the content version as in OpenResult.
	// Implementations without a cheap probe may report ErrUnsupported or a -1
	// size; the OpenSeeker then falls back to learning the size from an
	// OpenRange result.
	Size(validator string) (SizeResult, error)
}

Opener provides ranged access to a resource for building an io.ReadSeekCloser.

type Seeker

type Seeker struct {
	*OpenSeeker
	// contains filtered or unexported fields
}

Seeker reads an HTTP resource via Range requests, implementing io.ReadSeekCloser. It is not safe for concurrent use.

func NewRangeSeeker added in v0.6.0

func NewRangeSeeker(ctx context.Context, transport http.RoundTripper, req *http.Request, start, end int64) *Seeker

NewRangeSeeker creates a Seeker that reads a bounded byte range [start, end] from an HTTP endpoint. end is the inclusive end byte; -1 means open-ended (read to EOF). A negative start requests the suffix of the last end bytes.

func NewSeeker

func NewSeeker(ctx context.Context, transport http.RoundTripper, req *http.Request) *Seeker

NewSeeker creates a new Seeker for reading from an HTTP endpoint using a GET request.

func NewSeekerWithHTTPClient added in v0.4.0

func NewSeekerWithHTTPClient(ctx context.Context, httpClient HTTPClient, req *http.Request) *Seeker

NewSeekerWithHTTPClient creates a Seeker that includes HTTP client capabilities to handle redirects.

func NewSuffixSeeker added in v0.6.0

func NewSuffixSeeker(ctx context.Context, transport http.RoundTripper, req *http.Request, suffixLen int64) *Seeker

NewSuffixSeeker creates a Seeker that reads the last suffixLen bytes of an HTTP endpoint. The actual byte range is resolved from the server's Content-Range response.

func (*Seeker) Response

func (s *Seeker) Response() (*http.Response, error)

Response returns the first HTTP response received from the server.

type SizeResult added in v0.7.0

type SizeResult struct {
	// Size is the total size of the resource; -1 if unknown.
	Size int64
	// Validator identifies the content version; empty if none.
	Validator string
}

SizeResult is the outcome of a Size call.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址