A Go library for rendering unified diffs with ANSI coloring, line collapsing, and inline change highlighting.
Built on top of go-difflib for the diff computation.
- Simple one-line API for quick diffs
- JSON-aware diffing with automatic key sorting and normalization
- Unified diff output with line numbers and gutter
- ANSI color support with auto-detection (TTY)
- Collapses long context lines (>120 chars by default) with
(+N chars)suffix - Highlights character-level differences within changed lines
- Configurable via functional options
go get github.com/streamingfast/diffx// One-line string diff (no color)
result := diffx.Diff(before, after)
// Write to stdout (auto-detects TTY for color)
diffx.WriteDiff(os.Stdout, before, after)
// JSON diff — normalizes keys order and formatting
result, err := diffx.JSONDiff(before, after)
// JSON diff to writer
diffx.WriteJSONDiff(os.Stdout, before, after)// Returns a plain-text diff string (no ANSI color by default).
result := diffx.Diff(oldContent, newContent)
// Force color on.
result := diffx.Diff(oldContent, newContent, diffx.WithColor(true))// Writes diff to w, auto-detects color when w is a TTY.
err := diffx.WriteDiff(os.Stdout, oldContent, newContent)Both inputs are unmarshaled and re-marshaled with sorted keys and consistent indentation before diffing. This makes the diff stable regardless of original key ordering.
// String version.
result, err := diffx.JSONDiff(beforeJSON, afterJSON)
// Writer version.
err := diffx.WriteJSONDiff(os.Stdout, beforeJSON, afterJSON)For advanced use, create a UnifiedDiffReporter directly:
reporter := diffx.NewUnifiedDiffReporter(
diffx.WithColor(true),
diffx.WithMaxLineLength(80),
diffx.WithContextLines(5),
)
err := reporter.Report(os.Stdout, "expected.json", "actual.json", before, after)// Force color on/off (default: auto-detect TTY for writers, off for strings)
diffx.WithColor(true)
// Set max line length before collapsing (default: 120, 0 = disable)
diffx.WithMaxLineLength(80)
// Set number of context lines around each hunk (default: 3)
diffx.WithContextLines(5)| Element | Color |
|---|---|
| Gutter (no diff) | Gray |
| Gutter (removal) | Red |
| Gutter (addition) | Green |
Hunk header (@@) |
Gray |
| Context text | Default |
| Removed line | Red |
| Added line | Green |
| Inline diff highlight | Bold on tinted background (red/green) |
go run ./examples/basicApache 2.0