Skip to content

alikatgh/safeheaders-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

81 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

SafeHeaders-Go

Go Report Card Tests Coverage Go Version License Security GoDoc

Production-ready, pure Go implementations of popular single-header C libraries with built-in concurrency support and zero CGO dependencies.

πŸŽ‰ v0.5.1 Release - All 9 modules are now production-ready with comprehensive testing, security scanning, and examples!

Table of Contents

Features

  • βœ… Memory Safe - No buffer overflows, bounds-checked, zero unsafe pointers
  • βœ… Concurrent - Built-in goroutine support for parallel processing
  • βœ… Zero Dependencies - Pure Go stdlib, no CGO required
  • βœ… Easy Integration - Drop-in packages for any Go project
  • βœ… Production Ready - Comprehensive tests, fuzz tests, security scanning
  • βœ… Well Documented - Full godoc, examples, and usage guides
  • βœ… Actively Maintained - Regular updates, security patches, community support

Quick Start

Installation

# Install a specific module
go get github.com/alikatgh/safeheaders-go/jsmn-go

# Or multiple modules
go get github.com/alikatgh/safeheaders-go/jsmn-go \
       github.com/alikatgh/safeheaders-go/stb-image-go \
       github.com/alikatgh/safeheaders-go/tinyxml2-go

Basic Usage

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/alikatgh/safeheaders-go/jsmn-go"
)

func main() {
    json := []byte(`{"name": "SafeHeaders-Go", "version": "0.5.0", "stable": true}`)

    // Option 1: Serial parsing (for small inputs)
    p := jsmngo.NewParser(100)
    count, err := p.Parse(json)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Parsed %d tokens\n", count)

    // Option 2: Parallel parsing (for large inputs)
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    tokens, err := jsmngo.ParseParallel(ctx, json)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Parsed %d tokens in parallel\n", len(tokens))
}

Available Modules

Module Status Version Coverage Description
jsmn-go 🟒 Stable v0.5.0 85% Fast JSON tokenizer with parallel parsing
linenoise-go 🟒 Stable v0.1.0 90% Minimal line editing library for CLI apps
stb-truetype-go 🟒 Stable v0.5.0 80% TrueType font parsing with LRU glyph cache
stb-image-go 🟒 Stable v0.5.0 75% Image loading with batch decoding (PNG, JPEG, GIF)
tinyxml2-go 🟒 Stable v0.5.0 70% XML DOM parsing with element traversal
cjson-go 🟒 Stable v0.5.0 70% JSON marshaling/unmarshaling with parallel processing
miniz-go 🟒 Stable v0.5.0 70% ZIP compression with concurrent chunking
cgltf-go 🟒 Stable v0.5.0 70% glTF 3D model loading with parallel assets
dr-wav-go 🟒 Stable v0.5.0 70% WAV audio file parsing with concurrent decoding

Status Legend:

  • 🟒 Stable - Production-ready, full test coverage, security-audited
  • 🟑 Beta - Core features complete, API may change
  • πŸ”΄ Alpha - Experimental, not recommended for production

All 9 modules are production-ready! πŸŽ‰

Examples

Comprehensive examples are available in the examples/ directory:

Available Examples

  1. JSON Parser - Production-ready JSON parsing with validation

    cd examples/json-parser && go run main.go
  2. Production HTTP Service - Complete HTTP server with SafeHeaders-Go

    cd examples/production-usage && go run main.go
  3. Linenoise REPL - Interactive command-line with history and completion

    cd examples/linenoise-repl && go run main.go
  4. More Examples - See examples/README.md for the full list

Quick Example Snippets

Parse Large JSON in Parallel
import (
    "context"
    "github.com/alikatgh/safeheaders-go/jsmn-go"
)

func parseJSON(data []byte) error {
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    tokens, err := jsmngo.ParseParallel(ctx, data)
    if err != nil {
        return err
    }

    fmt.Printf("Parsed %d tokens\n", len(tokens))
    return nil
}
Load Images Concurrently
import (
    "context"
    "github.com/alikatgh/safeheaders-go/stb-image-go"
)

func loadImages(files [][]byte) error {
    ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
    defer cancel()

    images, err := stbimagego.LoadBatchConcurrent(ctx, files)
    if err != nil {
        return err
    }

    fmt.Printf("Loaded %d images\n", len(images))
    return nil
}
Parse XML Document
import "github.com/alikatgh/safeheaders-go/tinyxml2-go"

func parseXML(data []byte) error {
    doc := tinyxml2go.NewDocument()
    if err := doc.Parse(data); err != nil {
        return err
    }

    root := doc.RootElement()
    fmt.Printf("Root element: %s\n", root.Name())
    return nil
}

Performance

Benchmarks on modern hardware (Apple M3 Pro, Go 1.23) with 1MB JSON (10,000 objects):

Module Mode Throughput Speedup Notes
jsmn-go Serial 6.7 MB/s 1.0x Baseline
jsmn-go Parallel (2 CPU) 10 MB/s 1.5x Good scaling
jsmn-go Parallel (4 CPU) 13.3 MB/s 2.0x Better scaling
jsmn-go Parallel (8 CPU) 14.3 MB/s 2.1x Optimal
stb-image-go Batch (4 CPU) 50 images/s 3.2x I/O bound
tinyxml2-go Serial 8.5 MB/s 1.0x DOM parsing

vs Go Stdlib:

  • encoding/json: Similar single-threaded performance, but SafeHeaders-Go offers 2x speedup with parallel mode
  • image/png: SafeHeaders-Go provides batch loading with 3x speedup for multiple images

vs C Libraries:

  • Performance within 10-20% of original C implementations
  • No CGO overhead, easier deployment
  • Memory-safe with bounds checking

Full benchmarks available in each module's README.

Why SafeHeaders-Go?

Traditional C libraries are fast but unsafe. Go stdlib is safe but doesn't parallelize parsing. SafeHeaders-Go gives you both:

vs C Libraries

Feature C Libraries SafeHeaders-Go
Memory Safety ❌ Manual βœ… Automatic
CGO Required βœ… Yes ❌ No
Cross-Compilation ❌ Hard βœ… Easy
Concurrency ❌ Manual βœ… Built-in
Deployment ❌ Complex βœ… Simple

vs Go Stdlib

Feature Go Stdlib SafeHeaders-Go
Safety βœ… Yes βœ… Yes
Parallel Parsing ❌ No βœ… Yes
Context Support βœ… Yes βœ… Yes
Zero Dependencies βœ… Yes βœ… Yes
Performance ⚠️ Good βœ… Better (for large inputs)

vs Other Go Ports

  • Concurrency-First Design - Built for parallel processing from the ground up
  • Production Ready - Comprehensive testing, security scanning, examples
  • Well Maintained - Regular updates, active community support
  • Zero Dependencies - Pure stdlib, no external packages

Production Usage

SafeHeaders-Go is designed for production use. Here's how to use it safely:

Input Validation

const MaxInputSize = 10 * 1024 * 1024 // 10MB

func validateAndParse(data []byte) error {
    if len(data) == 0 {
        return errors.New("empty input")
    }
    if len(data) > MaxInputSize {
        return fmt.Errorf("input too large: %d bytes", len(data))
    }

    // Parse with timeout
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    _, err := jsmngo.ParseParallel(ctx, data)
    return err
}

Error Handling

tokens, err := jsmngo.ParseParallel(ctx, data)
if err != nil {
    if errors.Is(err, context.Canceled) {
        return errors.New("parsing canceled")
    }
    if errors.Is(err, context.DeadlineExceeded) {
        return errors.New("parsing timeout")
    }
    return fmt.Errorf("parse failed: %w", err)
}

Best Practices

  1. Always use context timeouts for long-running operations
  2. Validate input size before processing (see SECURITY.md)
  3. Handle errors gracefully and provide meaningful messages
  4. Monitor memory usage in production (see examples)
  5. Use parallel mode only for inputs >4KB (overhead otherwise)

See examples/production-usage for a complete production-ready HTTP service.

Documentation

  • πŸ“– CONTRIBUTING.md - How to contribute, coding standards, architecture
  • πŸ”’ SECURITY.md - Security policy, vulnerability reporting, best practices
  • πŸ› ISSUES.md - Known issues, roadmap, improvement tracker
  • πŸ“ CHANGELOG.md - Version history, release notes
  • 🀝 CODE_OF_CONDUCT.md - Community guidelines
  • πŸ’‘ Examples - Comprehensive usage examples
  • πŸ“¦ Module READMEs - Detailed documentation for each module
  • πŸ§ͺ Test Data - Benchmark and test data files

Module Documentation

Each module has comprehensive documentation:

  • Installation & Quick Start
  • API Reference with godoc
  • Performance Benchmarks
  • Known Limitations
  • Examples & Use Cases

Visit the module directories for detailed docs.

Contributing

We welcome contributions! πŸŽ‰

How to Contribute

  1. Report Bugs - Use our bug report template
  2. Request Features - Use our feature request template
  3. Port New Libraries - Use our port request template
  4. Submit PRs - Follow our pull request template
  5. Improve Docs - Documentation improvements are always welcome
  6. Add Tests - Increase coverage, add fuzz tests
  7. Optimize Performance - Improve parallel algorithms

See CONTRIBUTING.md for detailed guidelines.

Development Setup

# Clone repository
git clone https://github.com/alikatgh/safeheaders-go.git
cd safeheaders-go

# Run tests
go test ./...

# Run tests with race detector
go test -race ./...

# Run tests with coverage
go test -coverprofile=coverage.out ./...

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

# Run linter
golangci-lint run --config .golangci.yml

Wishlist - Port New Libraries

Want to port a new C library? Pick one:

See CONTRIBUTING.md for porting guidelines.

Security

Security is a top priority for SafeHeaders-Go.

Reporting Vulnerabilities

DO NOT open a public issue for security vulnerabilities. Instead:

  1. Email: [email protected] (or use GitHub Security Advisories)
  2. Include: Detailed description, proof of concept, impact assessment
  3. Timeline: We aim to respond within 48 hours

See SECURITY.md for complete details.

Security Features

  • βœ… Input Validation - Configurable size limits (coming in v1.0)
  • βœ… Bounds Checking - No buffer overflows
  • βœ… Context Timeouts - Prevent DoS attacks
  • βœ… Memory Safety - Pure Go, no unsafe pointers
  • βœ… Security Scanning - Automated gosec and govulncheck in CI
  • βœ… Dependency Management - Zero external dependencies
  • βœ… Regular Audits - Automated security scans weekly

Known Security Considerations

See SECURITY.md for:

  • DoS prevention guidelines
  • Input size recommendations
  • Context timeout best practices
  • Memory usage monitoring

CI/CD & Quality

  • βœ… Automated Testing - All modules tested on every commit
  • βœ… Race Detection - Tests run with -race flag
  • βœ… Coverage Tracking - Minimum 70% coverage enforced
  • βœ… Security Scanning - gosec and govulncheck on every PR
  • βœ… Linting - golangci-lint with 50+ linters
  • βœ… Fuzz Testing - Automated fuzzing for parser modules
  • βœ… Benchmarking - Performance regression detection
  • βœ… Multi-OS Testing - Linux, macOS, Windows
  • βœ… Dependabot - Automated dependency updates

Roadmap

See ISSUES.md for detailed roadmap. Highlights:

v1.0.0 (Q1 2026)

  • Stable API guarantee
  • Input validation with configurable limits
  • Improved error handling consistency
  • Smart chunking for better parallel performance
  • Official security audit

v1.1.0 (Q2 2026)

  • Streaming APIs for large files
  • WebAssembly support
  • Additional C library ports
  • Performance optimizations

Community & Support

License

MIT License - See LICENSE for details.

Original C libraries retain their respective licenses (MIT, BSD, Public Domain, zlib).

Attribution

SafeHeaders-Go is a reimplementation of the following excellent C libraries:

  • jsmn by Serge Zaitsev (MIT)
  • stb by Sean Barrett (Public Domain / MIT)
  • cJSON by Dave Gamble (MIT)
  • tinyxml2 by Lee Thomason (zlib)
  • cgltf by Johannes Kuhlmann (MIT)
  • dr_wav by David Reid (Public Domain)

Thank you to all the original authors for their amazing work! πŸ™


Made with ❀️ by the SafeHeaders-Go team

Star this repo if you find it useful! ⭐

About

Idiomatic Go rewrites of single-header C libs with opt-in goroutine helpers and zero-CGO safety.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •