Files
uberbringer/internal/pkg/escpos/builder.go
T
57_WolveandClaude Opus 5.5 6502d9551d
CI / Lint, test and scan (push) Successful in 1m41s
Refactor to Go standards; add print queue and own ESC/POS library
Restructure the daemon to follow the project's Go coding standards and
expand its features.

Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
  dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
  Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.

Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
  retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
  replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
  1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
  internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
  with live printer status, `secret` and `token` subcommands.

Fixes
- Jobs are validated before anything is sent; a failed printer dial no
  longer panics.
- Request logs never contain tokens; Sentry no longer receives the
  Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
  dedicated user and uses a current nginx TLS config.

config.toml is no longer tracked; start from configs/config.example.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:17:16 -06:00

182 lines
4.7 KiB
Go

// Package escpos builds Epson ESC/POS command streams for thermal receipt
// printers.
//
// A [Builder] accumulates commands in memory. Callers send [Builder.Bytes] to
// the printer in a single write, so an invalid element never leaves a
// half-printed receipt. Commands follow the Epson ESC/POS Application
// Programming Guide; byte values are named by the control characters the
// specification uses (ESC, GS, DLE).
package escpos
import (
"bytes"
"errors"
"fmt"
)
// Control characters that introduce ESC/POS commands.
const (
ht byte = 0x09
lf byte = 0x0A
dle byte = 0x10
eot byte = 0x04
esc byte = 0x1B
gs byte = 0x1D
)
// MaxCharacterScale is the largest character width or height multiplier
// supported by GS !.
const MaxCharacterScale = 8
// ErrInvalidArgument is wrapped by every validation error the package
// returns.
var ErrInvalidArgument = errors.New("escpos: invalid argument")
// Justification aligns text, barcodes and QR codes on the line.
type Justification byte
// Justification values for ESC a.
const (
JustifyLeft Justification = 0
JustifyCenter Justification = 1
JustifyRight Justification = 2
)
// Font selects one of the printer's built-in character fonts.
type Font byte
// Font values for ESC M.
const (
FontA Font = 0
FontB Font = 1
)
// Underline selects the underline thickness.
type Underline byte
// Underline values for ESC -.
const (
UnderlineNone Underline = 0
UnderlineThin Underline = 1
UnderlineThick Underline = 2
)
// CutMode selects a full or partial paper cut.
type CutMode byte
// CutMode values for GS V function B, which feeds the paper to the cutting
// position before cutting so the last printed line is not lost.
const (
CutFull CutMode = 65
CutPartial CutMode = 66
)
// Builder accumulates an ESC/POS command stream. The zero value is ready to
// use. A Builder is not safe for concurrent use.
type Builder struct {
buf bytes.Buffer
}
// Bytes returns the accumulated command stream. The slice aliases the
// Builder's buffer and is valid until the next write.
func (b *Builder) Bytes() []byte {
return b.buf.Bytes()
}
// Len returns the number of accumulated bytes.
func (b *Builder) Len() int {
return b.buf.Len()
}
// Raw appends p unchanged. It is the escape hatch for commands the Builder
// does not model.
func (b *Builder) Raw(p []byte) {
b.buf.Write(p)
}
// Text appends already-encoded character data. Use [CodePage.Encode] to
// convert UTF-8 text first.
func (b *Builder) Text(encoded []byte) {
b.buf.Write(encoded)
}
// Initialize resets the printer to its power-on settings (ESC @).
func (b *Builder) Initialize() {
b.buf.Write([]byte{esc, '@'})
}
// LineFeed prints the line buffer and advances one line (LF).
func (b *Builder) LineFeed() {
b.buf.WriteByte(lf)
}
// Feed prints the line buffer and advances lines lines (ESC d n).
func (b *Builder) Feed(lines uint8) {
b.buf.Write([]byte{esc, 'd', lines})
}
// LineSpacing sets the line spacing in motion units (ESC 3 n).
func (b *Builder) LineSpacing(units uint8) {
b.buf.Write([]byte{esc, '3', units})
}
// DefaultLineSpacing restores the default line spacing (ESC 2).
func (b *Builder) DefaultLineSpacing() {
b.buf.Write([]byte{esc, '2'})
}
// Bold turns emphasized printing on or off (ESC E n).
func (b *Builder) Bold(on bool) {
b.buf.Write([]byte{esc, 'E', boolByte(on)})
}
// Underline sets the underline mode (ESC - n).
func (b *Builder) Underline(u Underline) {
b.buf.Write([]byte{esc, '-', byte(u)})
}
// Reverse turns white-on-black printing on or off (GS B n).
func (b *Builder) Reverse(on bool) {
b.buf.Write([]byte{gs, 'B', boolByte(on)})
}
// Justify sets the alignment (ESC a n). It takes effect at the start of the
// next line.
func (b *Builder) Justify(j Justification) {
b.buf.Write([]byte{esc, 'a', byte(j)})
}
// Font selects the character font (ESC M n).
func (b *Builder) Font(f Font) {
b.buf.Write([]byte{esc, 'M', byte(f)})
}
// Size sets the character width and height multipliers, each 1 to
// [MaxCharacterScale] (GS ! n).
func (b *Builder) Size(width, height int) error {
if width < 1 || width > MaxCharacterScale || height < 1 || height > MaxCharacterScale {
return fmt.Errorf("%w: character size %dx%d must be within 1-%d",
ErrInvalidArgument, width, height, MaxCharacterScale)
}
b.buf.Write([]byte{gs, '!', byte(width-1)<<4 | byte(height-1)})
return nil
}
// SelectCodePage selects the character table used to print text (ESC t n).
func (b *Builder) SelectCodePage(cp CodePage) {
b.buf.Write([]byte{esc, 't', cp.table()})
}
// Cut feeds the paper to the cutter plus feed motion units and cuts it
// (GS V m n).
func (b *Builder) Cut(mode CutMode, feed uint8) {
b.buf.Write([]byte{gs, 'V', byte(mode), feed})
}
func boolByte(on bool) byte {
if on {
return 1
}
return 0
}