qrcode

package module
v2.0.0 Latest Latest
Warning

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

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

README

QRcode - Feature-rich QR code generation library for Go

Go Reference Go Version Zero Dependencies A high-performance, production-ready QR code generation library for Go. Zero external dependencies — pure stdlib only.

Features

  • 5 output formats — PNG, SVG, Terminal (ANSI), PDF, Base64 data URI
  • 35 payload types — Text, URL, WiFi, vCard, MeCard, SMS, Email, Geo, Calendar, PayPal, Crypto, Social media, and more
  • Fluent Builder API — Chain configuration for clean, readable code
  • Bounded batch processing — Built-in worker pool with configurable concurrency
  • Logo overlay — Embed logos with automatic resizing and tinting
  • Custom module styles — Rounded, circle, diamond, gradient, and transparent modules
  • Context support — Full context.Context propagation for cancellation and timeouts
  • Thread-safe — Mutex-protected configuration with lifecycle management
  • Zero dependencies — Pure Go standard library — no CGo, no external packages

Installation

go get github.com/os-gomod/qrcode

Quick Start

Text QR Code

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/os-gomod/qrcode"
    "github.com/os-gomod/qrcode/payload"
)

func main() {
    client := qrcode.MustNew(qrcode.WithDefaultSize(512))
    defer client.Close()

    data, err := client.Render(context.Background(),
        &payload.TextPayload{Text: "Hello, World!"},
        qrcode.FormatPNG,
    )
    if err != nil {
        panic(err)
    }
    os.WriteFile("qrcode.png", data, 0644)
    fmt.Println("QR code saved to qrcode.png")
}

URL QR Code

data, _ := client.Render(ctx,
    &payload.URLPayload{URL: "https://example.com"},
    qrcode.FormatPNG,
)

WiFi QR Code

data, _ := client.Render(ctx,
    &payload.WiFiPayload{
        SSID:       "MyNetwork",
        Password:   "password123",
        Encryption: "WPA2",
    },
    qrcode.FormatPNG,
)

SVG Output

svg, _ := client.Render(ctx,
    &payload.TextPayload{Text: "https://example.com"},
    qrcode.FormatSVG,
)
os.WriteFile("qrcode.svg", svg, 0644)

Save to File

The Save method infers the format from the file extension:

_ = client.Save(ctx, &payload.TextPayload{Text: "Hello"}, "output.png")  // PNG
_ = client.Save(ctx, &payload.TextPayload{Text: "Hello"}, "output.svg")  // SVG
_ = client.Save(ctx, &payload.TextPayload{Text: "Hello"}, "output.pdf")  // PDF

One-Liner Helpers

For simple use cases, the package-level Quick* functions create a temporary client, render, and close automatically:

// PNG bytes
png, _ := qrcode.Quick("Hello, World!", 256)

// SVG string
svg, _ := qrcode.QuickSVG("Hello, World!", 256)

// Save directly to file
_ = qrcode.QuickFile("Hello, World!", "output.png", 512)

// URL QR code
urlQR, _ := qrcode.QuickURL("https://example.com")

// WiFi QR code
wifiQR, _ := qrcode.QuickWiFi("MyNetwork", "password123", "WPA2")

// vCard QR code
vcardQR, _ := qrcode.QuickContact("John", "Doe", "+1234567890", "john@example.com")

// SMS QR code
smsQR, _ := qrcode.QuickSMS("+1234567890", "Hi there!")

// Email QR code
emailQR, _ := qrcode.QuickEmail("hello@example.com", "Subject", "Body")

// Geo-location QR code
geoQR, _ := qrcode.QuickGeo(37.7749, -122.4194)

// Calendar event QR code
eventQR, _ := qrcode.QuickEvent("Meeting", "Room 1", start, end)

// PayPal payment QR code
payQR, _ := qrcode.QuickPayment("pay@example.com", "25.00")

Builder API

The fluent Builder API provides a clean way to configure complex QR codes:

client, err := qrcode.NewBuilder().
    Size(512).
    ErrorCorrection(qrcode.LevelH).
    Margin(8).
    ForegroundColor("#FF0000").
    BackgroundColor("#FFFFFF").
    Logo("logo.png", 0.25).
    WorkerCount(8).
    Build()
if err != nil {
    panic(err)
}
defer client.Close()

The Builder also supports Quick* helpers that inherit the builder's configuration:

b := qrcode.NewBuilder().
    Size(256).
    ForegroundColor("#1A56DB").
    BackgroundColor("#F0F9FF")

png, _ := b.Quick("Custom branded QR code")
svg, _ := b.QuickSVG("Custom branded QR code")
_ = b.QuickFile("Custom branded QR code", "branded.png")
urlQR, _ := b.QuickURL("https://example.com")

All Output Formats

client := qrcode.MustNew()
ctx := context.Background()
p := &payload.TextPayload{Text: "Hello, World!"}

// PNG (raster image)
png, _ := client.Render(ctx, p, qrcode.FormatPNG)

// SVG (vector — scales to any size)
svg, _ := client.Render(ctx, p, qrcode.FormatSVG)

// Terminal (ANSI block characters for CLI output)
terminal, _ := client.Render(ctx, p, qrcode.FormatTerminal)

// PDF (embeddable in documents)
pdf, _ := client.Render(ctx, p, qrcode.FormatPDF)

// Base64 data URI (for embedding in HTML <img> tags)
b64, _ := client.Render(ctx, p, qrcode.FormatBase64)

Payload Types (35 total)

# Payload Type Key Fields
1 Text TextPayload Text string
2 URL URLPayload URL string, Title string
3 WiFi WiFiPayload SSID, Password, Encryption, Hidden bool
4 vCard VCardPayload FirstName, LastName, Phone, Email, Organization, Title, URL, Address, Note
5 MeCard MeCardPayload Name, Phone, Email, URL, Birthday, Note, Address, Nickname
6 SMS SMSPayload Phone string, Message string
7 MMS MMSPayload Phone, Subject, Message
8 Phone PhonePayload Number string
9 Email EmailPayload To, Subject, Body, CC []string
10 Geo GeoPayload Latitude, Longitude float64
11 Calendar CalendarPayload Title, Description, Location, Start, End time.Time, AllDay bool
12 Event Ticket EventPayload EventID, EventName, Venue, StartTime, Category, Seat, Organizer, Description, URL
13 PayPal PayPalPayload Username, Amount, Currency, Reference
14 Crypto CryptoPayload Address, Amount, CryptoType
15 Twitter TwitterPayload Username string
16 Twitter Follow TwitterFollowPayload Username string
17 Instagram InstagramPayload Username string
18 Facebook FacebookPayload PageURL string
19 LinkedIn LinkedInPayload ProfileURL string
20 Telegram TelegramPayload Username string
21 YouTube Video YouTubeVideoPayload VideoID string
22 YouTube Channel YouTubeChannelPayload ChannelID string
23 Spotify Track SpotifyTrackPayload TrackID string
24 Spotify Playlist SpotifyPlaylistPayload PlaylistID string
25 Apple Music AppleMusicTrackPayload TrackID, StoreFront string
26 WhatsApp WhatsAppPayload Phone, Message
27 Zoom ZoomPayload MeetingID, Password, DisplayName
28 Google Maps GoogleMapsPayload Latitude, Longitude, Query, Zoom int
29 Google Maps Place GoogleMapsPlacePayload PlaceName string
30 Google Maps Directions GoogleMapsDirectionsPayload Origin, Destination, TravelMode
31 Apple Maps AppleMapsPayload Latitude, Longitude, Query
32 App Store/Google Play MarketPayload Platform, PackageID, AppName, Campaign
33 iBeacon IBeaconPayload UUID, Major, Minor int, Manufacturer
34 NTP Locale NTPLocalePayload Host, Port, Version int, Description
35 PID PIDPayload See payload/pid.go for fields

Advanced Features

Batch Processing

Generate multiple QR codes concurrently with a bounded worker pool:

client := qrcode.MustNew(qrcode.WithWorkerCount(8))
defer client.Close()

payloads := []payload.Payload{
    &payload.TextPayload{Text: "item-1"},
    &payload.TextPayload{Text: "item-2"},
    &payload.TextPayload{Text: "item-3"},
}
results, _ := client.Batch(ctx, payloads)

Advanced batch with the batch package:

import "github.com/os-gomod/qrcode/batch"

proc := batch.NewProcessor(client,
    batch.WithBatchFormat(qrcode.FormatPNG),
    batch.WithBatchConcurrency(8),
)

items := []batch.Item{
    {ID: "qr1", Data: "Hello"},
    {ID: "qr2", Data: "World"},
}

results, stats, _ := proc.ProcessWithStats(ctx, items)
fmt.Printf("Generated %d QR codes in %v (avg: %v)\n", stats.Total, stats.TotalTime, stats.AvgTime)

Custom Renderer Options

Use the public renderer re-exports for fine-grained rendering control:

import (
    "bytes"
    qrcode "github.com/os-gomod/qrcode"
    "github.com/os-gomod/qrcode/payload"
)

qr, _ := client.Generate(ctx, &payload.TextPayload{Text: "Styled"})

var buf bytes.Buffer
pngR := qrcode.NewPNGRenderer()
data, _ := pngR.Render(ctx, qr,
    qrcode.WithModuleStyle(&qrcode.ModuleStyle{
        Shape:        "rounded",
        Roundness:    0.3,
        Transparency: 1.0,
    }),
    qrcode.WithForegroundColor("#FF0000"),
    qrcode.WithBackgroundColor("#FFFFFF"),
)
buf.Write(data)

Module Styles

The PNG renderer supports custom module shapes:

// Rounded modules
pngR.Render(ctx, qr, &buf,
    qrcode.WithModuleStyle(&qrcode.ModuleStyle{
        Shape:        "rounded",
        Roundness:    0.5,
        Transparency: 1.0,
    }),
)

// Circle modules (convenience helper)
pngR.Render(ctx, qr, &buf,
    qrcode.WithCircleModules(),
    qrcode.WithForegroundColor("#DC2626"),
)

// Diamond modules
pngR.Render(ctx, qr, &buf,
    qrcode.WithModuleStyle(&qrcode.ModuleStyle{
        Shape:        "diamond",
        Roundness:    0,
        Transparency: 1.0,
    }),
    qrcode.WithForegroundColor("#7C3AED"),
)

// Gradient foreground
pngR.Render(ctx, qr, &buf,
    qrcode.WithGradient("#059669", "#0891B2", 135),
)

Logo Overlay

client, _ := qrcode.New(
    qrcode.WithDefaultSize(400),
    qrcode.WithErrorCorrection(qrcode.LevelH),
    qrcode.WithLogo("logo.png", 0.25),
)
defer client.Close()

data, _ := client.Render(ctx, &payload.URLPayload{URL: "https://example.com"}, qrcode.FormatPNG)

Or use the logo package for manual control:

import "github.com/os-gomod/qrcode/logo"

logoProc := logo.New("logo.png", 0.25)
logoImg, _ := logoProc.Load()

// Render QR, then overlay:
resizedLogo := logo.ResizeLogo(logoImg, qr.Size, 0.25)
final := logo.OverlayLogo(qrImage, resizedLogo, 4)

Structured Error Handling

import qrerrors "github.com/os-gomod/qrcode/errors"

if err != nil {
    if qrerrors.IsCode(err, qrerrors.ErrCodeValidation) {
        // Handle validation errors
    }
    if qrerrors.IsCode(err, qrerrors.ErrCodeEncoding) {
        // Handle encoding errors
    }
}

Configuration Options

Option Description Default
WithDefaultSize(int) Output image size in pixels (100–4000) 300
WithVersion(int) QR version (1–40), 0 for auto 0
WithMinVersion(int) Minimum QR version 1
WithMaxVersion(int) Maximum QR version 40
WithAutoSize(bool) Automatic version selection true
WithErrorCorrection(ECLevel) Error correction level (L/M/Q/H) M
WithECLevel(ECLevel) Canonical alias for WithErrorCorrection M
WithQuietZone(int) Quiet zone (margin) in modules (0–20) 4
WithWorkerCount(int) Max concurrent workers for batch (1–64) 4
WithQueueSize(int) Internal queue size 1024
WithDefaultFormat(Format) Default output format FormatPNG
WithForegroundColor(string) Foreground hex color #000000
WithBackgroundColor(string) Background hex color #FFFFFF
WithMaskPattern(int) Mask pattern (-1 for auto, 0–7) -1
WithLogo(string, float64) Logo source path and size ratio (0.05–0.4) disabled
WithLogoOverlay(bool) Enable/disable logo overlay false
WithLogoTint(string) Tint color applied to the logo disabled
WithPrefix(string) Filename prefix for batch output disabled

Client Interface

type Client interface {
    Generate(ctx context.Context, p payload.Payload) (*encoding.QRCode, error)
    GenerateWithOptions(ctx context.Context, p payload.Payload, opts ...Option) (*encoding.QRCode, error)
    GenerateToWriter(ctx context.Context, p payload.Payload, w io.Writer, format Format) error
    Render(ctx context.Context, p payload.Payload, format Format) ([]byte, error)
    Save(ctx context.Context, p payload.Payload, path string) error
    Batch(ctx context.Context, payloads []payload.Payload, opts ...Option) ([]*encoding.QRCode, error)
    Close() error
    SetOptions(opts ...Option) error
    Closed() bool
}

Constructors:

client, err := qrcode.New(opts ...)            // Returns error on invalid config
client := qrcode.MustNew(opts ...)             // Panics on invalid config
client, err := qrcode.NewClient(opts ...)      // Alias for New()
client := qrcode.MustNewClient(opts ...)       // Alias for MustNew()

Benchmarks

Run benchmarks with:

go test -bench=. -benchmem ./...

See benchmark_test.go for the full benchmark suite, which covers:

  • BenchmarkQuick — One-liner PNG generation
  • BenchmarkQuickSVG — One-liner SVG generation
  • BenchmarkGenerate — Client-based QR encoding
  • BenchmarkGenerateWithOptions — Per-call option overrides
  • BenchmarkRender_PNG — PNG rendering pipeline
  • BenchmarkRender_SVG — SVG rendering pipeline
  • BenchmarkRender_Terminal — Terminal output rendering
  • BenchmarkGenerateToWriter_SVG — Stream-based SVG output
  • BenchmarkBatch — Concurrent batch generation (50 items)
  • BenchmarkNew — Client construction overhead
  • BenchmarkBuilder — Builder pattern construction
  • BenchmarkEncode — Low-level QR matrix encoding

Testing

# Run all tests with race detection and coverage
go test ./... -race -cover

# Run a specific package
go test ./payload/... -race -cover

# Run with verbose output
go test ./... -race -cover -v

# Run benchmarks
go test -bench=. -benchmem ./...

Migration from v1

See docs/MIGRATION.md for the complete v1 to v2 migration guide.

Key Changes

  • Generator is a type alias for Client — existing code compiles unchanged
  • ErrorCorrectionLevel is a type alias for ECLevel
  • Close(context.Context) changed to Close() error
  • Package-level render functions removed — use client.Render() instead
  • New canonical names: NewClient, MustNewClient, WithECLevel

Architecture

See docs/ADR.md for Architecture Decision Records covering:

  • Layered architecture with internal/ packages
  • Payload interface design
  • Storage abstraction for file I/O
  • Worker pool for batch processing
  • Singleflight deduplication
  • Functional options pattern
  • Renderer registry pattern

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT

Documentation

Overview

Package qrcode provides a high-performance QR code generation library in pure Go with zero external dependencies.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BoolP

func BoolP(v bool) *bool

BoolP returns a pointer to a bool value.

func ContextWithQR

func ContextWithQR(ctx context.Context, client Client) context.Context

ContextWithQR stores a Client in a context value.

func DefaultModuleStyle

func DefaultModuleStyle() *renderer.ModuleStyle

DefaultModuleStyle is a convenience re-export.

func DurationP

func DurationP(v time.Duration) *time.Duration

DurationP returns a pointer to a time.Duration value.

func Float64P

func Float64P(v float64) *float64

Float64P returns a pointer to a float64 value.

func GetRenderer

func GetRenderer(f Format) (renderer.Renderer, error)

GetRenderer returns the renderer for the given format. This re-export allows consumers to access renderers without importing internal packages.

func IntP

func IntP(v int) *int

IntP returns a pointer to an int value.

func NewBase64Renderer

func NewBase64Renderer() *renderer.Base64Renderer

NewBase64Renderer returns a new Base64 renderer for direct use.

func NewPDFRenderer

func NewPDFRenderer() *renderer.PDFRenderer

NewPDFRenderer returns a new PDF renderer for direct use.

func NewPNGRenderer

func NewPNGRenderer() *renderer.PNGRenderer

NewPNGRenderer returns a new PNG renderer for direct use.

func NewSVGRenderer

func NewSVGRenderer() *renderer.SVGRenderer

NewSVGRenderer returns a new SVG renderer for direct use.

func NewTerminalRenderer

func NewTerminalRenderer() *renderer.TerminalRenderer

NewTerminalRenderer returns a new terminal renderer for direct use.

func Quick

func Quick(data string, size ...int) ([]byte, error)

Quick generates a QR code as PNG bytes for the given text data.

func QuickContact

func QuickContact(firstName, lastName, phone, email string, size ...int) ([]byte, error)

QuickContact generates a vCard QR code as PNG bytes.

func QuickEmail

func QuickEmail(to, subject, body string, size ...int) ([]byte, error)

QuickEmail generates an email QR code as PNG bytes.

func QuickEvent

func QuickEvent(title, location string, start, end time.Time, size ...int) ([]byte, error)

QuickEvent generates a calendar event QR code as PNG bytes.

func QuickFile

func QuickFile(data, path string, size ...int) error

QuickFile generates a QR code and saves it to a file. The output format is inferred from the file extension (.png, .svg, .pdf, .txt).

func QuickGeo

func QuickGeo(lat, lng float64, size ...int) ([]byte, error)

QuickGeo generates a geo-location QR code as PNG bytes.

func QuickPayment

func QuickPayment(username, amount string, size ...int) ([]byte, error)

QuickPayment generates a PayPal payment QR code as PNG bytes.

func QuickSMS

func QuickSMS(phone, message string, size ...int) ([]byte, error)

QuickSMS generates an SMS QR code as PNG bytes.

func QuickSVG

func QuickSVG(data string, size ...int) (string, error)

QuickSVG generates a QR code as an SVG string for the given text data.

func QuickURL

func QuickURL(url string, size ...int) ([]byte, error)

QuickURL generates a URL QR code as PNG bytes.

func QuickWiFi

func QuickWiFi(ssid, password, encryption string, size ...int) ([]byte, error)

QuickWiFi generates a WiFi QR code as PNG bytes.

func StringP

func StringP(v string) *string

StringP returns a pointer to a string value.

func ValidatePatch

func ValidatePatch(patch *ConfigPatch) error

ValidatePatch checks a ConfigPatch for invalid values before applying. Only non-nil fields are validated. Returns nil if all set fields are valid.

Types

type Builder

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

Builder provides a fluent API for constructing a Client. It is a convenience wrapper — all actual generation is delegated to the Client.

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new Builder with default configuration.

func (*Builder) AutoSize

func (b *Builder) AutoSize(auto bool) *Builder

AutoSize enables or disables automatic version selection.

func (*Builder) BackgroundColor

func (b *Builder) BackgroundColor(color string) *Builder

BackgroundColor sets the background color (hex, e.g., "#FFFFFF").

func (*Builder) Build

func (b *Builder) Build() (Client, error)

Build creates a new Client from the accumulated options.

func (*Builder) Clone

func (b *Builder) Clone() *Builder

Clone creates a copy of the builder with the same options.

func (*Builder) ErrorCorrection

func (b *Builder) ErrorCorrection(level ECLevel) *Builder

ErrorCorrection sets the error correction level.

func (*Builder) ForegroundColor

func (b *Builder) ForegroundColor(color string) *Builder

ForegroundColor sets the foreground color (hex, e.g., "#000000").

func (*Builder) Format

func (b *Builder) Format(f Format) *Builder

Format sets the default output format.

func (b *Builder) Logo(source string, sizeRatio float64) *Builder

Logo sets a logo image to overlay on the QR code.

func (*Builder) LogoOverlay

func (b *Builder) LogoOverlay(enabled bool) *Builder

LogoOverlay enables or disables logo overlay.

func (*Builder) LogoTint

func (b *Builder) LogoTint(color string) *Builder

LogoTint sets the tint color applied to the logo.

func (*Builder) Margin

func (b *Builder) Margin(margin int) *Builder

Margin sets the quiet zone (margin) around the QR code.

func (*Builder) MaskPattern

func (b *Builder) MaskPattern(pattern int) *Builder

MaskPattern sets the mask pattern (-1 for auto, 0-7).

func (*Builder) MaxVersion

func (b *Builder) MaxVersion(v int) *Builder

MaxVersion sets the maximum QR code version.

func (*Builder) MinVersion

func (b *Builder) MinVersion(v int) *Builder

MinVersion sets the minimum QR code version.

func (*Builder) MustBuild

func (b *Builder) MustBuild() Client

MustBuild creates a new Client, panicking on error.

func (*Builder) Options

func (b *Builder) Options(opts ...Option) *Builder

Options appends raw Option functions to the builder.

func (*Builder) Prefix

func (b *Builder) Prefix(prefix string) *Builder

Prefix sets a filename prefix for batch output.

func (*Builder) QueueSize

func (b *Builder) QueueSize(n int) *Builder

QueueSize sets the internal queue size.

func (*Builder) Quick

func (b *Builder) Quick(data string, size ...int) ([]byte, error)

Quick generates a QR code as PNG bytes for the given text data.

func (*Builder) QuickContact

func (b *Builder) QuickContact(firstName, lastName, phone, email string, size ...int) ([]byte, error)

QuickContact generates a vCard QR code as PNG bytes.

func (*Builder) QuickEmail

func (b *Builder) QuickEmail(to, subject, body string, size ...int) ([]byte, error)

QuickEmail generates an email QR code as PNG bytes.

func (*Builder) QuickEvent

func (b *Builder) QuickEvent(title, location string, start, end time.Time, size ...int) ([]byte, error)

QuickEvent generates a calendar event QR code as PNG bytes.

func (*Builder) QuickFile

func (b *Builder) QuickFile(data, path string, size ...int) error

QuickFile generates a QR code and saves it to a file.

func (*Builder) QuickGeo

func (b *Builder) QuickGeo(lat, lng float64, size ...int) ([]byte, error)

QuickGeo generates a geo-location QR code as PNG bytes.

func (*Builder) QuickPayment

func (b *Builder) QuickPayment(username, amount string, size ...int) ([]byte, error)

QuickPayment generates a PayPal QR code as PNG bytes.

func (*Builder) QuickSMS

func (b *Builder) QuickSMS(phone, message string, size ...int) ([]byte, error)

QuickSMS generates an SMS QR code as PNG bytes.

func (*Builder) QuickSVG

func (b *Builder) QuickSVG(data string, size ...int) (string, error)

QuickSVG generates a QR code as an SVG string for the given text data.

func (*Builder) QuickURL

func (b *Builder) QuickURL(url string, size ...int) ([]byte, error)

QuickURL generates a URL QR code as PNG bytes.

func (*Builder) QuickWiFi

func (b *Builder) QuickWiFi(ssid, password, encryption string, size ...int) ([]byte, error)

QuickWiFi generates a WiFi QR code as PNG bytes.

func (*Builder) Size

func (b *Builder) Size(size int) *Builder

Size sets the default output image size in pixels.

func (*Builder) Version

func (b *Builder) Version(v int) *Builder

Version sets the QR code version (1-40), or 0 for auto.

func (*Builder) WorkerCount

func (b *Builder) WorkerCount(n int) *Builder

WorkerCount sets the maximum concurrent workers for batch operations.

type Client

type Client interface {
	// Generate encodes a payload into a QR code matrix without rendering.
	// Returns the raw QR code structure (modules, version, size).
	Generate(ctx context.Context, p payload.Payload) (*encoding.QRCode, error)

	// GenerateWithOptions encodes a payload with per-call option overrides.
	// Options are applied to a copy of the client's config — the client's
	// default configuration is not modified.
	GenerateWithOptions(ctx context.Context, p payload.Payload, opts ...Option) (*encoding.QRCode, error)

	// GenerateToWriter encodes a payload, renders it, and writes the result
	// to w in the specified format. This is the streaming variant of Render
	// for callers who want to pipe output directly (e.g., HTTP responses).
	GenerateToWriter(ctx context.Context, p payload.Payload, w io.Writer, format Format) error

	// Render encodes a payload and returns the rendered output as bytes.
	// This is the unified replacement for the former GeneratePNG/SVG/ASCII/Base64 functions.
	Render(ctx context.Context, p payload.Payload, format Format) ([]byte, error)

	// Save encodes a payload, renders it, and writes the result to a file.
	// The output format is inferred from the file extension (.png, .svg, .pdf, .txt, .b64).
	Save(ctx context.Context, p payload.Payload, path string) error

	// Batch generates multiple QR codes concurrently with bounded worker count.
	// Results are returned in the same order as the input payloads.
	// Optional per-call options are applied uniformly to all items.
	Batch(ctx context.Context, payloads []payload.Payload, opts ...Option) ([]*encoding.QRCode, error)

	// Close releases all resources held by the client.
	// After Close is called, all other methods return ErrCodeClosed errors.
	Close() error

	// SetOptions updates the client's default configuration.
	// The new configuration is validated before being applied.
	// This is safe for concurrent use.
	SetOptions(opts ...Option) error

	// Closed reports whether the client has been closed.
	Closed() bool
}

Client is the primary interface for QR code generation and rendering. It is the stable public contract that all implementations must satisfy. Use New() or NewClient() to create instances; avoid depending on the concrete generator type directly.

All methods accept context.Context as the first parameter, enabling cancellation, timeout, and observability propagation.

func MustNew

func MustNew(opts ...Option) Client

MustNew creates a new Client, panicking on invalid configuration. Use this only in package-level init functions or tests where failure is fatal.

func MustNewClient

func MustNewClient(opts ...Option) Client

MustNewClient creates a new Client, panicking on invalid configuration.

func New

func New(opts ...Option) (Client, error)

New creates a new Client with the given options. It validates the configuration before returning; an error is returned for invalid configurations (e.g., size outside 100-4000, worker count outside 1-64).

This is the primary constructor for the QR code library.

func NewClient

func NewClient(opts ...Option) (Client, error)

NewClient creates a new Client with the given options. This is the recommended constructor name for v2 code.

func QRFromContext

func QRFromContext(ctx context.Context) (Client, bool)

QRFromContext retrieves a Client from a context value.

type Config

type Config struct {
	DefaultVersion  int           `json:"default_version"`
	DefaultECLevel  string        `json:"default_ec_level"`
	MinVersion      int           `json:"min_version"`
	MaxVersion      int           `json:"max_version"`
	AutoSize        bool          `json:"auto_size"`
	WorkerCount     int           `json:"worker_count"`
	QueueSize       int           `json:"queue_size"`
	DefaultFormat   string        `json:"default_format"`
	DefaultSize     int           `json:"default_size"`
	QuietZone       int           `json:"quiet_zone"`
	ForegroundColor string        `json:"foreground_color"`
	BackgroundColor string        `json:"background_color"`
	MaskPattern     int           `json:"mask_pattern"`
	LogoSource      string        `json:"logo_source"`
	LogoSizeRatio   float64       `json:"logo_size_ratio"`
	LogoOverlay     bool          `json:"logo_overlay"`
	LogoTint        string        `json:"logo_tint"`
	Prefix          string        `json:"prefix"`
	SlowOperation   time.Duration `json:"slow_operation"`
}

Config holds all configuration for QR code generation. Fields use value types (not pointers) for straightforward usage. To selectively override specific fields without zero-value ambiguity, use ConfigPatch with ApplyPatch.

func ApplyPatch

func ApplyPatch(base *Config, patch *ConfigPatch) *Config

ApplyPatch applies all non-nil fields from patch to base, returning a new Config. The original base is not modified.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a shallow copy of the config.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the config for invalid values and returns an error describing the first problem found.

type ConfigPatch

type ConfigPatch struct {
	DefaultVersion  *int
	DefaultECLevel  *string
	MinVersion      *int
	MaxVersion      *int
	AutoSize        *bool
	WorkerCount     *int
	QueueSize       *int
	DefaultFormat   *string
	DefaultSize     *int
	QuietZone       *int
	ForegroundColor *string
	BackgroundColor *string
	MaskPattern     *int
	LogoSource      *string
	LogoSizeRatio   *float64
	LogoOverlay     *bool
	LogoTint        *string
	Prefix          *string
	SlowOperation   *time.Duration
}

ConfigPatch provides explicit, zero-value-safe overrides for Config. Only fields that are non-nil are applied — nil fields are treated as "no change", eliminating the ambiguity of the old Merge method where zero values (0, "", false) could not be distinguished from "not set".

Example:

patch := ConfigPatch{
    WorkerCount: intPtr(8),
    AutoSize:    boolPtr(false),
}
cfg := ApplyPatch(defaultConfig(), &patch)

func ConfigToPatch

func ConfigToPatch(c *Config) ConfigPatch

ConfigToPatch creates a ConfigPatch from a Config, where every field is set. This is useful when you want to serialize or compare a full config as a patch.

type ECLevel

type ECLevel int

ECLevel represents the QR code error correction level. Higher levels provide more error recovery capability but reduce data capacity.

const (
	// LevelL (Low) — ~7% of codewords can be restored.
	LevelL ECLevel = iota
	// LevelM (Medium) — ~15% of codewords can be restored.
	LevelM
	// LevelQ (Quartile) — ~25% of codewords can be restored.
	LevelQ
	// LevelH (High) — ~30% of codewords can be restored.
	LevelH
)

func (ECLevel) String

func (l ECLevel) String() string

type Format

type Format int

Format represents the output format for a rendered QR code.

const (
	// FormatPNG encodes the QR code as a PNG image.
	FormatPNG Format = iota
	// FormatSVG encodes the QR code as an SVG document.
	FormatSVG
	// FormatTerminal encodes the QR code as terminal/ANSI block characters.
	FormatTerminal
	// FormatPDF encodes the QR code as a PDF document.
	FormatPDF
	// FormatBase64 encodes the QR code as a Base64 data URL (PNG-based).
	FormatBase64
)

func FormatFromPath

func FormatFromPath(path string) Format

FormatFromPath returns the QR format inferred from a file path's extension.

func (Format) Extension

func (f Format) Extension() string

Extension returns the common file extension for the format (with leading dot). Returns ".png" as the default for unknown formats.

func (Format) String

func (f Format) String() string

type ModuleStyle

type ModuleStyle = renderer.ModuleStyle

ModuleStyle is a type alias for the internal renderer's ModuleStyle, exposed for convenience when using GetRenderer or New*Renderer directly.

type Option

type Option func(*Config)

func WithAutoSize

func WithAutoSize(auto bool) Option

func WithBackgroundColor

func WithBackgroundColor(color string) Option

func WithDefaultFormat

func WithDefaultFormat(f Format) Option

func WithDefaultSize

func WithDefaultSize(size int) Option

func WithErrorCorrection

func WithErrorCorrection(level ECLevel) Option

func WithForegroundColor

func WithForegroundColor(color string) Option
func WithLogo(logoSource string, sizeRatio float64) Option

func WithLogoOverlay

func WithLogoOverlay(enabled bool) Option

func WithLogoTint

func WithLogoTint(color string) Option

func WithMaskPattern

func WithMaskPattern(pattern int) Option

func WithMaxVersion

func WithMaxVersion(v int) Option

func WithMinVersion

func WithMinVersion(v int) Option

func WithPrefix

func WithPrefix(prefix string) Option

func WithQueueSize

func WithQueueSize(n int) Option

func WithQuietZone

func WithQuietZone(zone int) Option

func WithSlowOperation

func WithSlowOperation(d time.Duration) Option

func WithVersion

func WithVersion(v int) Option

func WithWorkerCount

func WithWorkerCount(n int) Option

type RenderOption

type RenderOption = renderer.RenderOption

RenderOption is a type alias for the internal renderer's RenderOption.

func WithCircleModules

func WithCircleModules() RenderOption

WithCircleModules is a convenience re-export.

func WithGradient

func WithGradient(startColor, endColor string, angle float64) RenderOption

WithGradient is a convenience re-export.

func WithModuleStyle

func WithModuleStyle(style *renderer.ModuleStyle) RenderOption

WithModuleStyle is a convenience re-export.

func WithRoundedModules

func WithRoundedModules(roundness float64) RenderOption

WithRoundedModules is a convenience re-export.

func WithTransparency

func WithTransparency(alpha float64) RenderOption

WithTransparency is a convenience re-export.

Directories

Path Synopsis
Package errors provides enterprise-grade error handling for the QR code library.
Package errors provides enterprise-grade error handling for the QR code library.
examples
api-server command
Package main implements a minimal HTTP API server for QR code generation.
Package main implements a minimal HTTP API server for QR code generation.
basic command
Package main demonstrates basic QR code generation using the qrcode library.
Package main demonstrates basic QR code generation using the qrcode library.
batch command
Package main demonstrates batch QR code generation using the batch.Processor.
Package main demonstrates batch QR code generation using the batch.Processor.
cli command
Package main implements a simple CLI tool for QR code generation.
Package main implements a simple CLI tool for QR code generation.
concurrent command
Package main demonstrates concurrent QR code generation using both client.Batch() and batch.Processor with ProcessWithStats.
Package main demonstrates concurrent QR code generation using both client.Batch() and batch.Processor with ProcessWithStats.
custom-config command
Package main demonstrates custom configuration options for QR code generation.
Package main demonstrates custom configuration options for QR code generation.
logo-overlay command
Package main demonstrates logo overlay on QR codes.
Package main demonstrates logo overlay on QR codes.
multi-format command
Package main generates the same QR code in all 5 supported formats: PNG, SVG, Terminal, PDF, and Base64.
Package main generates the same QR code in all 5 supported formats: PNG, SVG, Terminal, PDF, and Base64.
internal
renderer
Package renderer provides modular, pure-rendering QR code output formats.
Package renderer provides modular, pure-rendering QR code output formats.
storage
Package storage provides file system abstraction for QR code output.
Package storage provides file system abstraction for QR code output.
workerpool
Package workerpool provides a generic, bounded-concurrency worker pool.
Package workerpool provides a generic, bounded-concurrency worker pool.

Jump to

Keyboard shortcuts

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