batch

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package batch provides concurrent batch processing for QR code generation with support for file output, JSON/CSV input parsing, and per-item statistics.

The package is designed around the Processor type, which orchestrates concurrent QR code generation using a configurable worker pool. Input can be supplied programmatically via Item slices or parsed from JSON and CSV readers.

Quick Start

For simple use cases where you just need PNG bytes for a list of strings, use QuickBatch:

pngs, err := batch.QuickBatch(ctx, []string{"hello", "world"})

Processor

For more control over output format, concurrency, and file saving:

gen, _ := qrcode.New(qrcode.WithDefaultSize(256))
proc := batch.NewProcessor(gen,
    batch.WithBatchConcurrency(8),
    batch.WithBatchFormat(qrcode.FormatPNG),
)
results, err := proc.Process(ctx, items)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BatchGenerateWithStats

func BatchGenerateWithStats(ctx context.Context, gen qrcode.Generator, items []Item, opts ...ProcessorOption) ([]Result, *BatchStats, error)

BatchGenerateWithStats is a convenience function that creates a Processor with the given options and calls Processor.ProcessWithStats, returning results along with per-item timing statistics.

func QuickBatch

func QuickBatch(ctx context.Context, dataList []string, size ...int) ([][]byte, error)

QuickBatch generates PNG QR codes for a list of text strings. It creates a temporary generator with the given image size (default 256) and returns a slice of PNG byte slices aligned with the input. Individual items that fail are represented by nil entries; the returned error aggregates any failures.

Types

type BatchStats

type BatchStats struct {
	// Total is the total number of items in the batch.
	Total int
	// Succeeded is the number of items that completed without error.
	Succeeded int
	// Failed is the number of items that encountered an error.
	Failed int
	// TotalTime is the wall-clock duration of the entire batch run.
	TotalTime time.Duration
	// AvgTime is the average per-item generation duration (successful items only).
	AvgTime time.Duration
	// MinTime is the fastest single-item generation duration.
	MinTime time.Duration
	// MaxTime is the slowest single-item generation duration.
	MaxTime time.Duration
}

BatchStats holds performance statistics for a batch run.

Timings reflect per-item wall-clock durations and are only meaningful when concurrency is factored in (TotalTime is the overall elapsed time).

type Item

type Item struct {
	// ID is an optional identifier used for file naming and error correlation.
	ID string
	// Data is the raw text to encode when no Payload is provided.
	Data string
	// Payload is a pre-built payload for encoding. Takes precedence over Data.
	Payload payload.Payload
}

Item represents a single QR code generation task in a batch.

Either Data (plain text) or Payload (a pre-built payload) should be set. If both are provided, Payload takes precedence. The optional ID field is used for file naming when saving results and for correlating errors.

type Processor

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

Processor handles batch QR code generation with configurable concurrency, output format, and optional file saving.

Use NewProcessor to create a Processor with optional configuration via ProcessorOption functions.

func NewProcessor

func NewProcessor(gen qrcode.Generator, opts ...ProcessorOption) *Processor

NewProcessor creates a new batch processor with the given QR code generator and optional configuration. The processor uses 4 concurrent workers and PNG output format by default.

func (*Processor) FromCSV

func (p *Processor) FromCSV(_ context.Context, reader io.Reader) ([]Item, error)

FromCSV parses CSV data from reader into a slice of Item values. The first row is treated as a header. A required "data" column provides the text to encode; an optional "id" column is used for file naming. Headers are case-insensitive and leading whitespace is trimmed.

func (*Processor) FromJSON

func (p *Processor) FromJSON(_ context.Context, reader io.Reader) ([]Item, error)

FromJSON parses a JSON array of objects from reader into a slice of Item values. Each object must have a "data" field; an optional "id" field is used for file naming. Example input:

[{"id": "item1", "data": "https://example.com"}]

func (*Processor) Process

func (p *Processor) Process(ctx context.Context, items []Item) ([]Result, error)

Process generates QR codes for all items concurrently, returning a slice of results aligned by index with the input. If an output directory is configured, results are also saved to disk. Returns nil if the input is empty. The returned error aggregates any per-item failures.

func (*Processor) ProcessWithStats

func (p *Processor) ProcessWithStats(ctx context.Context, items []Item) ([]Result, *BatchStats, error)

ProcessWithStats generates QR codes for all items and returns detailed per-item timing statistics in addition to the results. Statistics include total/average/min/max generation durations and success/failure counts.

func (*Processor) SaveToDir

func (p *Processor) SaveToDir(ctx context.Context, items []Item, outputDir string) ([]Result, error)

SaveToDir generates QR codes for all items and saves them as files in the specified output directory. The directory is created if needed. Each file is named after the item ID (or its index) with the appropriate extension for the configured format. PNG is used as the default format.

type ProcessorOption

type ProcessorOption func(*Processor)

ProcessorOption configures a Processor during construction.

Options are applied in order and may be composed.

func WithBatchConcurrency

func WithBatchConcurrency(n int) ProcessorOption

WithBatchConcurrency sets the number of concurrent workers used during batch processing. Defaults to 4 if not specified. Values less than 1 are ignored.

func WithBatchFormat

func WithBatchFormat(f qrcode.Format) ProcessorOption

WithBatchFormat sets the output format for batch results and enables format rendering in the Data field of each Result. Supported formats include PNG, SVG, PDF, Terminal, and Base64.

func WithBatchOutputDir

func WithBatchOutputDir(dir string) ProcessorOption

WithBatchOutputDir sets the directory where generated QR code files are written. The directory is created automatically if it does not exist.

type Result

type Result struct {
	// ID is the identifier from the corresponding Item.
	ID string
	// QRCode is the encoded QR code matrix (nil on error).
	QRCode *encoding.QRCode
	// Data is the rendered image bytes in the configured format (nil if not rendering).
	Data []byte
	// Err holds any error encountered during generation.
	Err error
	// Path is the filesystem path of the saved file (empty if not saved to disk).
	Path string
}

Result holds the output of a single batch item.

On success, QRCode contains the encoded matrix and Data contains the rendered image bytes (if a format was configured). Path is populated when results are saved to disk. On failure, Err is non-nil.

func BatchSaveToDir

func BatchSaveToDir(ctx context.Context, gen qrcode.Generator, items []Item, outputDir string, opts ...ProcessorOption) ([]Result, error)

BatchSaveToDir is a convenience function that creates a Processor with the given options and calls Processor.SaveToDir, generating QR codes and saving them as files in the specified output directory.

Jump to

Keyboard shortcuts

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