warc

package module
v0.0.0-...-57dab90 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: CC0-1.0 Imports: 42 Imported by: ? modules, 0 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

warc

GoDoc Go Report Card

A Go library for reading and writing WARC files, with advanced features for web archiving.

Features

  • Read and write WARC files with support for multiple compression formats (GZIP, ZSTD)
  • HTTP client with built-in WARC recording capabilities
  • Content deduplication (local URL-agnostic and CDX-based)
  • Configurable file rotation and size limits
  • DNS caching and custom DNS resolution (with DNS archiving)
  • Custom TLS configurations
  • Random local IP assignment for distributed crawling (including Linux kernel AnyIP feature)
  • Smart memory management with disk spooling options
  • IPv4/IPv6 support with configurable preferences

Installation

go get github.com/internetarchive/gowarc

Usage

This library's biggest feature is to provide a standard HTTP client through which you can execute requests that will be recorded automatically to WARC files. It's the basis of Zeno.

HTTP Client with WARC Recording
package main

import (
	"context"
	"io"

	http "github.com/saveweb/fhttp"
	warc "github.com/saveweb/gowarc"
)

func main() {
	// Configure WARC settings
	rotator := warc.NewRotatorSettings("crawler.example.com")
	rotator.Prefix = "WEB"
	rotator.OutputDirectory = "./warcs"
	// WARC record IDs use UUIDv7 by default. Use UUIDv4 when compatibility
	// with a consumer that requires random UUIDs is needed.
	// rotator.RecordIDVersion = warc.UUIDv4

	// Configure HTTP client settings
	clientSettings := warc.HTTPClientSettings{
		RotatorSettings: rotator,
		TempDir:         "./temp",
		EnableHTTP2:     true,
		// Keepalive is enabled by default. Set DisableKeepAlives only when
		// connection reuse is intentionally unwanted.
	}

	// Create HTTP client
	client, err := warc.NewWARCWritingHTTPClient(clientSettings)
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://archive.org", nil)
	if err != nil {
		panic(err)
	}
	exchange, startErr := client.Start(req)
	if exchange == nil {
		panic(startErr)
	}
	// Releases the capture on every early-return path. Once Commit succeeds,
	// this deferred Discard cannot change the decision.
	defer exchange.Discard(context.Background())
	if startErr != nil {
		// Commit includes the Start error in its complete result. Do not join
		// startErr again, or the same transport failure will be printed twice.
		_, err := exchange.Commit(context.Background())
		panic(err)
	}
	// Process response
	_, _ = io.Copy(io.Discard, exchange.Response.Body)
	_ = exchange.Response.Body.Close()
	// Keep the exchange and wait until its records reach the WARC writer.
	if _, err := exchange.Commit(context.Background()); err != nil {
		panic(err)
	}
	finalized, err := client.Shutdown(context.Background())
	if err != nil {
		panic(err)
	}
	_ = finalized.FinalizedFiles
}

HTTP/1 captures contain the plaintext HTTP/1 wire bytes seen by the transport. HTTP/2 and HTTP/3 captures are deterministic application/http serializations of the actual stream headers, body data, and trailers. Closing a response body early performs a bounded drain; if the message boundary cannot be reached, Exchange.Commit reports a truncated attempt. To reject a capture after inspecting its response, call Exchange.Discard; it closes any unread response body and releases the captured temporary data.

HTTP exchanges are written in request-then-response order by default. Set rotator.UseInternetArchiveRecordOrder = true for IA-compatible response-then-request order.

CLI Tools

In addition to the Go library, gowarc provides several command-line utilities for working with WARC files:

Installation

Pre-built releases are available on the GitHub releases page.

# Install from source
go install github.com/internetarchive/gowarc/cmd/warc@latest

# Or build locally
cd cmd/warc/
go build -o warc
Available Commands
warc extract

Extract files and content from WARC archives with filtering options.

# Extract all files from WARC archives
warc extract file1.warc.gz file2.warc.gz

# Extract only specific content types
warc extract --content-type "text/html" --content-type "image/jpeg" archive.warc.gz

# Extract to specific directory with multiple threads  
warc extract --output ./extracted --threads 4 *.warc.gz

# Sort extracted files by host
warc extract --host-sort archive.warc.gz
warc mend

Repair and close incomplete gzip-compressed WARC files that were left with .open suffix during crawling.

# Dry run to see what would be fixed
warc mend --dry-run *.warc.gz.open

# Fix files with confirmation prompts  
warc mend corrupted.warc.gz.open

# Auto-fix without prompts
warc mend --yes *.warc.gz.open

# Force verification of any gzip WARC files (not just .open)
warc mend --force --dry-run archive.warc.gz

Features:

  • By default, only processes .open files; use --force to verify any gzip WARC files
  • Verifies gzip format using magic bytes, not just file extension
  • Detects and removes trailing garbage bytes
  • Truncates at corruption points while preserving maximum valid data
  • Removes .open suffix to "close" files when present
  • Provides comprehensive statistics on repairs performed
  • Memory-efficient streaming for large files

See cmd/warc/mend/README.md for detailed documentation.

warc verify

Validate the integrity and structure of WARC files.

# Verify single file
warc verify archive.warc.gz

# Verify multiple files with progress
warc verify -v *.warc.gz

# JSON output for automation
warc verify --json archive.warc.gz
warc completion

Generate shell completion scripts for bash, zsh, fish, or PowerShell.

# Bash completion
warc completion bash > /etc/bash_completion.d/warc

# Zsh completion
warc completion zsh > ~/.zsh/completions/_warc

# Fish completion
warc completion fish > ~/.config/fish/completions/warc.fish

# PowerShell completion
warc completion powershell > warc.ps1
Global Flags

All commands support these global options:

  • -v, --verbose - Enable verbose/debug logging
  • --json - Output logs in JSON format for structured processing
  • -h, --help - Show help for any command

Build tags

  • standard_gzip: Use the standard library gzip implementation instead of the faster one from klauspost
  • klauspost_gzip: Use the faster gzip implementation from klauspost (default, you don't need to specify it)

License

This module is released under CC0 license. You can find a copy of the CC0 License in the LICENSE file.

Documentation

Index

Constants

View Source
const (
	CompressionNone = compressionType("none")
	CompressionGzip = compressionType("gzip")
	CompressionZstd = compressionType("zstd")
)
View Source
const (
	ContextKeyFeedback contextKey = "feedback"
)

Variables

View Source
var (
	IPv6 *availableIPs
	IPv4 *availableIPs
)
View Source
var (
	// Create a couple of counters for tracking various stats
	DataTotal atomic.Int64

	CDXDedupeTotalBytes          atomic.Int64
	DoppelgangerDedupeTotalBytes atomic.Int64
	LocalDedupeTotalBytes        atomic.Int64

	CDXDedupeTotal          atomic.Int64
	DoppelgangerDedupeTotal atomic.Int64
	LocalDedupeTotal        atomic.Int64
)
View Source
var CompressionTypes = []compressionType{CompressionNone, CompressionGzip, CompressionZstd}
View Source
var DedupeHTTPClient = http.Client{
	Timeout: 10 * time.Second,
	Transport: &http.Transport{
		Dial: (&net.Dialer{
			Timeout: 5 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 5 * time.Second,
	},
}
View Source
var ErrExchangeAlreadyDecided = errors.New("warc: exchange already has a different decision")
View Source
var ErrUnknownDigestAlgorithm = errors.New("unknown digest algorithm")

Functions

func GetDigest

func GetDigest(r io.Reader, digestAlgorithm DigestAlgorithm) (string, error)

func GetNextIP

func GetNextIP(availableIPs *availableIPs) net.IP

func IsDigestSupported

func IsDigestSupported(algorithm string) bool

func MustCompressionTypeFromString

func MustCompressionTypeFromString(s string) compressionType

func WithFeedbackChannel

func WithFeedbackChannel(ctx context.Context, feedbackChan chan FeedbackEvent) context.Context

Types

type AttemptResult

type AttemptResult struct {
	Protocol string
	Outcome  http.CaptureOutcome
	Records  FeedbackEvent
	Err      error
	// contains filtered or unexported fields
}

AttemptResult describes the archival outcome of one actual transport attempt. A retried logical request can therefore contain more than one result.

type Compressor

type Compressor interface {
	io.Writer // Embedded so the compressor can be used as an io.Writer and its underlying writer can be replaced via Reset.
	io.Closer
	Reset(io.Writer)
}

type CustomHTTPClient

type CustomHTTPClient struct {
	WaitGroup *WaitGroupWithCount

	ErrChan    chan *Error
	WARCWriter chan *RecordBatch

	TempDir string

	TLSHandshakeTimeout   time.Duration
	ResponseHeaderTimeout time.Duration
	ConnReadDeadline      time.Duration

	DigestAlgorithm DigestAlgorithm

	DataTotal *atomic.Int64

	DecompressBody bool

	CDXDedupeTotalBytes          *atomic.Int64
	DoppelgangerDedupeTotalBytes *atomic.Int64
	LocalDedupeTotalBytes        *atomic.Int64

	CDXDedupeTotal          *atomic.Int64
	DoppelgangerDedupeTotal *atomic.Int64
	LocalDedupeTotal        *atomic.Int64
	// contains filtered or unexported fields
}

func NewWARCWritingHTTPClient

func NewWARCWritingHTTPClient(HTTPClientSettings HTTPClientSettings) (httpClient *CustomHTTPClient, err error)

func (*CustomHTTPClient) Close

func (c *CustomHTTPClient) Close() error

Close is the compatibility form of Shutdown.

func (*CustomHTTPClient) CloseIdleConnections

func (c *CustomHTTPClient) CloseIdleConnections()

func (*CustomHTTPClient) Do

func (c *CustomHTTPClient) Do(req *http.Request) (*http.Response, error)

func (*CustomHTTPClient) Get

func (c *CustomHTTPClient) Get(url string) (*http.Response, error)

func (*CustomHTTPClient) Head

func (c *CustomHTTPClient) Head(url string) (*http.Response, error)

func (*CustomHTTPClient) Post

func (c *CustomHTTPClient) Post(url, contentType string, body interface{}) (*http.Response, error)

func (*CustomHTTPClient) Shutdown

func (c *CustomHTTPClient) Shutdown(ctx context.Context) (FinalizeResult, error)

Shutdown stops new work and waits for every active capture and WARC writer to finish. The returned filenames have been flushed, closed and renamed. ctx controls only how long the caller waits; shutdown itself continues.

func (*CustomHTTPClient) Start

func (c *CustomHTTPClient) Start(req *http.Request) (*Exchange, error)

Start executes req and returns an Exchange that the caller must finish with Commit or Discard after inspecting the response. Start can return both a non-nil Exchange and an error when a failed transport attempt was captured. Commit includes that Start error in its complete result, so callers must not join the two errors.

func (*CustomHTTPClient) WriteBatch

func (c *CustomHTTPClient) WriteBatch(ctx context.Context, batch *RecordBatch) (WriteResult, error)

WriteBatch submits a caller-constructed batch and waits for its writer result.

func (*CustomHTTPClient) WriteRecord

func (c *CustomHTTPClient) WriteRecord(targetURI, warcType, contentType, payloadString string, payloadReader io.Reader)

WriteRecord is retained for source compatibility. New code should use WriteRecordContext so archival failure is part of normal error handling.

func (*CustomHTTPClient) WriteRecordContext

func (c *CustomHTTPClient) WriteRecordContext(ctx context.Context, targetURI, warcType, contentType, payloadString string, payloadReader io.Reader) (RecordEvent, error)

WriteRecordContext writes one non-HTTP WARC record and returns only after the writer has accepted it. Once submitted, the writer result is authoritative even if ctx is canceled concurrently.

type DedupeOptions

type DedupeOptions struct {
	CDXURL             string
	DoppelgangerHost   string
	CDXCookie          string
	SizeThreshold      int
	DedupeCacheSize    int
	LocalDedupe        bool
	CDXDedupe          bool
	DoppelgangerDedupe bool
}

type DigestAlgorithm

type DigestAlgorithm int
const (
	SHA1 DigestAlgorithm = iota
	// According to IIPC, lowercase base 16 is the "popular" encoding for SHA256
	SHA256Base16
	SHA256Base32
	BLAKE3
)

func GetDigestFromPrefix

func GetDigestFromPrefix(prefix string) DigestAlgorithm

type Error

type Error struct {
	Err  error
	Func string
}

type Exchange

type Exchange struct {
	Response *http.Response
	// contains filtered or unexported fields
}

Exchange separates receiving response headers from the decision to retain the capture. Callers consume or close Response.Body, then finish with either Commit or Discard.

func (*Exchange) Commit

func (e *Exchange) Commit(ctx context.Context) (ExchangeResult, error)

Commit retains every transport attempt belonging to the logical request and waits until its records have been accepted by a WARC writer. Repeating Commit is harmless and returns the same result. Its result includes any error already returned by Start for this exchange.

func (*Exchange) Discard

func (e *Exchange) Discard(ctx context.Context) error

Discard closes any response body and releases every transport attempt without writing HTTP records. Repeating Discard is harmless.

type ExchangeResult

type ExchangeResult struct {
	Attempts []AttemptResult
	Records  FeedbackEvent
	Err      error
}

ExchangeResult is complete only after every transport attempt has finished and every retained WARC batch has been accepted by a writer.

type FeedbackEvent

type FeedbackEvent []RecordEvent // WARC-Record-ID header values of the records that have been written

type FinalizeResult

type FinalizeResult struct {
	FinalizedFiles []string
	Err            error
}

type GzipReaderInterface

type GzipReaderInterface interface {
	io.ReadCloser
	Multistream(enable bool)
	Reset(r io.Reader) error
}

GzipReaderInterface defines the interface for gzip readers This allows us to switch between standard gzip and klauspost gzip based on build tags

type GzipWriterInterface

type GzipWriterInterface interface {
	io.WriteCloser
	Flush() error
	Reset(w io.Writer)
}

GzipWriterInterface defines the interface for gzip writers This allows us to switch between standard gzip and klauspost gzip based on build tags

type HTTPClientSettings

type HTTPClientSettings struct {
	RotatorSettings         *RotatorSettings
	TempDir                 string
	DNSServers              []string
	DNSFallback             *dns.ClientConfig
	DedupeOptions           DedupeOptions
	DialTimeout             time.Duration
	ResponseHeaderTimeout   time.Duration
	DNSResolutionTimeout    time.Duration
	DNSRecordsTTL           time.Duration
	DNSCacheSize            int
	DNSConcurrency          int
	TLSHandshakeTimeout     time.Duration
	ConnReadDeadline        time.Duration
	DecompressBody          bool
	FollowRedirects         bool
	InsecureSkipVerifyCerts bool
	RandomLocalIP           bool
	DisableIPv4             bool
	DisableIPv6             bool
	IPv6AnyIP               bool
	DigestAlgorithm         DigestAlgorithm
	DisableKeepAlives       bool
	DefaultUserAgent        string
	ClientProfile           profiles.ClientProfile
	RandomTLSExtensionOrder bool
	MaxIdleConns            int
	MaxIdleConnsPerHost     int
	IdleConnTimeout         time.Duration
	EarlyCloseDrainLimit    int64
	EarlyCloseDrainTimeout  time.Duration
	MaxConcurrentDrains     int
	EnableHTTP2             bool
	EnableHTTP3             bool
	ForceProtocol           string // "http/1.1", "h2", "h3"
}
type Header map[string][]string

func NewHeader

func NewHeader() Header

func (Header) Add

func (h Header) Add(key, value string)

func (Header) Del

func (h Header) Del(key string)

func (Header) Get

func (h Header) Get(key string) string

func (Header) Set

func (h Header) Set(key, value string)

func (Header) Values

func (h Header) Values(key string) []string

type ReadOpts

type ReadOpts int

ReadOpts are options for ReadRecord

const (
	// ReadOptsNoContentOutput means that the content of the record should not be returned.
	// This is useful for reading only the headers or metadata of the record.
	ReadOptsNoContentOutput ReadOpts = iota
)

type Reader

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

Reader stores the bufio.Reader and gzip.Reader for a WARC file

func NewReader

func NewReader(reader io.Reader) (*Reader, error)

NewReader returns a new WARC reader

func (*Reader) Close

func (r *Reader) Close() error

Close closes the WARC reader src and dec readers if they are open.

func (*Reader) ReadRecord

func (r *Reader) ReadRecord(opts ...ReadOpts) (*Record, error)

ReadRecord reads the next record from the opened WARC file.

Returns:

  • *Record: Record guaranteed to be non-nil if no errors occurred.
  • error: any parsing/IO error encountered (io.EOF for clean EOF).

type Record

type Record struct {
	RecordInfo
	Content spooledtempfile.ReadWriteSeekCloser
}

Record represents a WARC record.

func NewRecord

func NewRecord(tempDir string) *Record

NewRecord creates a new WARC record.

type RecordBatch

type RecordBatch struct {
	FeedbackChan chan FeedbackEvent
	CaptureTime  string
	Records      []*Record
	// contains filtered or unexported fields
}

RecordBatch is a structure that contains a bunch of records to be written at the same time, and a common capture timestamp. FeedbackChan is used to signal when the records have been written.

func NewRecordBatch

func NewRecordBatch(feedbackChan chan FeedbackEvent) *RecordBatch

NewRecordBatch creates a record batch, it also initialize the capture time.

func (*RecordBatch) Wait

func (b *RecordBatch) Wait(ctx context.Context) (WriteResult, error)

type RecordEvent

type RecordEvent struct {
	RecordInfo
	WARCFilename string // WARC filename, no .open extension
}

a record that has been written to a WARC file.

type RecordInfo

type RecordInfo struct {
	Header  Header
	Offset  int64  // Offset of the record start (-1 if WARC file type is not supported yet)
	Size    int64  // COMPRESSED size of the record (gzip member): header + deflate data + trailer. (-1 if WARC file type is not supported yet)
	Version string // WARC/1.0, WARC/1.1 ...
}

type RotatorSettings

type RotatorSettings struct {
	// Content of the warcinfo record that will be written
	// to all WARC files
	WarcinfoContent Header
	// Prefix used for WARC filenames, WARC 1.1 specifications
	// recommend to name files this way:
	// Prefix-Timestamp-Serial-Crawlhost.warc.gz
	Prefix string
	// Compression algorithm to use
	Compression compressionType

	// Path to a ZSTD compression dictionary to embed (and use) in .warc.zst files
	CompressionDictionary string
	// Directory where the created WARC files will be stored,
	// default will be the current directory
	OutputDirectory string
	// WARCSize is in Megabytes
	WARCSize float64
	// WARCWriterPoolSize defines the number of parallel WARC writers
	WARCWriterPoolSize int
	// RecordIDVersion selects the UUID version for generated WARC record IDs.
	// The default is UUIDv7.
	RecordIDVersion UUIDVersion
	// UseInternetArchiveRecordOrder writes each HTTP exchange as response then
	// request. The default order is request then response.
	//
	// IA has a quirk of placing response records at the beginning - They claim
	// this benefits performance, but I've thought about it for two years without
	// figuring out why.
	UseInternetArchiveRecordOrder bool
	// contains filtered or unexported fields
}

RotatorSettings is used to store the settings needed by recordWriter to write WARC files

func NewRotatorSettings

func NewRotatorSettings(hostname string) *RotatorSettings

NewRotatorSettings creates a RotatorSettings structure and initialize it with default values

func (*RotatorSettings) NewWARCRotator

func (s *RotatorSettings) NewWARCRotator() (recordWriterChan chan *RecordBatch, doneChannels []chan bool, err error)

NewWARCRotator creates and return a channel that can be used to communicate records to be written to WARC files to the recordWriter function running in a goroutine

type TLSProfile

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

func DefaultTLSProfile

func DefaultTLSProfile() *TLSProfile

func NewTLSProfile

func NewTLSProfile(profile profiles.ClientProfile, randomExtOrder bool) *TLSProfile

type UUIDVersion

type UUIDVersion string

UUIDVersion selects the UUID version used for generated WARC record IDs.

const (
	UUIDv4 UUIDVersion = "v4"
	UUIDv7 UUIDVersion = "v7"
)

type WaitGroupWithCount

type WaitGroupWithCount struct {
	sync.WaitGroup
	// contains filtered or unexported fields
}

func (*WaitGroupWithCount) Add

func (wg *WaitGroupWithCount) Add(delta int)

func (*WaitGroupWithCount) Done

func (wg *WaitGroupWithCount) Done()

func (*WaitGroupWithCount) Size

func (wg *WaitGroupWithCount) Size() int

type WriteResult

type WriteResult struct {
	Events FeedbackEvent
	Err    error
}

type Writer

type Writer struct {
	Compressor      Compressor
	BufWriter       *bufio.Writer
	FileName        string
	DigestAlgorithm DigestAlgorithm
	RecordIDVersion UUIDVersion
	ParallelGZIP    bool
}

Writer writes WARC records to WARC files.

func NewWriter

func NewWriter(writer io.Writer, fileName string, digestAlgorithm DigestAlgorithm, compression compressionType, newFileCreation bool, dictionary []byte) (*Writer, error)

NewWriter creates a new WARC writer.

func (*Writer) FlushAndCloseCompressor

func (w *Writer) FlushAndCloseCompressor() (err error)

Close will flush the final output and close the stream. The function will block until everything has been written. The Compressor can still be re-used after calling this. If the Compressor is nil, this will just flush the Writer.BufWriter.

func (*Writer) Reset

func (w *Writer) Reset(output io.Writer)

reset resets the compressed writer to write to a new output. This reuses the encoder's internal buffers.

func (*Writer) WriteInfoRecord

func (w *Writer) WriteInfoRecord(payload Header) (recordID string, err error)

WriteInfoRecord method can be used to write an information record to the WARC file and flush the data

func (*Writer) WriteRecord

func (w *Writer) WriteRecord(r *Record) (recordID string, err error)

WriteRecord writes a record to the underlying WARC file and flushes the data. A record consists of a version string, the record header followed by a record content block and two newlines:

Version CLRF
Header-Key: Header-Value CLRF
CLRF
Content
CLRF
CLRF

Directories

Path Synopsis
cmd
testfetch command
warc command
pkg

Jump to

Keyboard shortcuts

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