jsonschema

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2025 License: MIT Imports: 5 Imported by: 0

README

JSON Schema Module for Modular

Go Reference Modules CI

A Modular module that provides JSON Schema validation capabilities.

Overview

The JSON Schema module provides a service for validating JSON data against JSON Schema specifications. It wraps github.com/santhosh-tekuri/jsonschema/v6 to provide a clean, service-oriented interface that integrates with the Modular framework.

Features

  • Compile JSON schemas from file paths or URLs
  • Validate JSON data in multiple formats:
    • Raw JSON bytes
    • io.Reader interface
    • Go interface{} values
  • Simple integration with other Modular modules

Installation

go get github.com/CrisisTextLine/modular/modules/jsonschema@v1.0.0

Usage

Registering the Module
import (
    "github.com/CrisisTextLine/modular"
    "github.com/CrisisTextLine/modular/modules/jsonschema"
)

func main() {
    app := modular.NewStdApplication(
        modular.NewStdConfigProvider(nil),
        logger,
    )
    
    // Register the JSON Schema module
    app.RegisterModule(jsonschema.NewModule())
    
    // Register your modules that depend on the schema service
    app.RegisterModule(NewYourModule())
    
    // Run the application
    if err := app.Run(); err != nil {
        logger.Error("Application error", "error", err)
    }
}
Using the JSON Schema Service
type YourModule struct {
    schemaService jsonschema.JSONSchemaService
}

// Request the JSON Schema service
func (m *YourModule) RequiresServices() []modular.ServiceDependency {
    return []modular.ServiceDependency{
        {
            Name:               "jsonschema.service",
            Required:           true,
            SatisfiesInterface: reflect.TypeOf((*jsonschema.JSONSchemaService)(nil)).Elem(),
        },
    }
}

// Inject the service using constructor injection
func (m *YourModule) Constructor() modular.ModuleConstructor {
    return func(app *modular.StdApplication, services map[string]any) (modular.Module, error) {
        schemaService, ok := services["jsonschema.service"].(jsonschema.JSONSchemaService)
        if !ok {
            return nil, fmt.Errorf("service 'jsonschema.service' not found or wrong type")
        }
        
        return &YourModule{
            schemaService: schemaService,
        }, nil
    }
}

// Example of using the schema service
func (m *YourModule) ValidateData(schemaPath string, data []byte) error {
    // Compile the schema
    schema, err := m.schemaService.CompileSchema(schemaPath)
    if err != nil {
        return fmt.Errorf("failed to compile schema: %w", err)
    }
    
    // Validate data against the schema
    if err := m.schemaService.ValidateBytes(schema, data); err != nil {
        return fmt.Errorf("validation failed: %w", err)
    }
    
    return nil
}

API Reference

Types
Schema
type Schema interface {
    // Validate validates the given value against the JSON schema
    Validate(value interface{}) error
}
JSONSchemaService
type JSONSchemaService interface {
    // CompileSchema compiles a JSON schema from a file path or URL
    CompileSchema(source string) (Schema, error)
    
    // ValidateBytes validates raw JSON data against a compiled schema
    ValidateBytes(schema Schema, data []byte) error
    
    // ValidateReader validates JSON from an io.Reader against a compiled schema
    ValidateReader(schema Schema, reader io.Reader) error
    
    // ValidateInterface validates a Go interface{} against a compiled schema
    ValidateInterface(schema Schema, data interface{}) error
}

License

MIT License

Documentation

Overview

Package jsonschema provides JSON Schema validation capabilities for the modular framework.

This module integrates JSON Schema validation into the modular framework, allowing applications to validate JSON data against predefined schemas. It supports schema compilation from files or URLs and provides multiple validation methods for different data sources.

Features

The jsonschema module provides the following capabilities:

  • JSON Schema compilation from files, URLs, or embedded schemas
  • Validation of JSON data from multiple sources (bytes, readers, interfaces)
  • Error reporting with detailed validation failure information
  • Service interface for dependency injection
  • Support for JSON Schema draft versions through underlying library
  • Thread-safe schema compilation and validation

Schema Sources

Schemas can be loaded from various sources:

Service Registration

The module registers a JSON schema service for dependency injection:

// Get the JSON schema service
schemaService := app.GetService("jsonschema.service").(jsonschema.JSONSchemaService)

// Compile a schema
schema, err := schemaService.CompileSchema("/path/to/user-schema.json")

// Validate JSON data
err = schemaService.ValidateBytes(schema, jsonData)

Usage Examples

Schema compilation and basic validation:

// Compile a schema from file
schema, err := schemaService.CompileSchema("./schemas/user.json")
if err != nil {
    return fmt.Errorf("failed to compile schema: %w", err)
}

// Validate JSON bytes
jsonData := []byte(`{"name": "John", "age": 30}`)
err = schemaService.ValidateBytes(schema, jsonData)
if err != nil {
    return fmt.Errorf("validation failed: %w", err)
}

Validating different data sources:

// Validate from HTTP request body
err = schemaService.ValidateReader(schema, request.Body)

// Validate Go structs/interfaces
userData := map[string]interface{}{
    "name": "Alice",
    "age":  25,
    "email": "alice@example.com",
}
err = schemaService.ValidateInterface(schema, userData)

HTTP API validation example:

func validateUserHandler(schemaService jsonschema.JSONSchemaService) http.HandlerFunc {
    // Compile schema once at startup
    userSchema, err := schemaService.CompileSchema("./schemas/user.json")
    if err != nil {
        log.Fatal("Failed to compile user schema:", err)
    }

    return func(w http.ResponseWriter, r *http.Request) {
        // Validate request body against schema
        if err := schemaService.ValidateReader(userSchema, r.Body); err != nil {
            http.Error(w, "Invalid request: "+err.Error(), http.StatusBadRequest)
            return
        }

        // Process valid request...
    }
}

Configuration validation:

// Validate application configuration
configSchema, err := schemaService.CompileSchema("./schemas/config.json")
if err != nil {
    return err
}

configData := map[string]interface{}{
    "database": map[string]interface{}{
        "host": "localhost",
        "port": 5432,
    },
    "logging": map[string]interface{}{
        "level": "info",
    },
}

if err := schemaService.ValidateInterface(configSchema, configData); err != nil {
    return fmt.Errorf("invalid configuration: %w", err)
}

Schema Definition Examples

User schema example (user.json):

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "age"],
  "additionalProperties": false
}

Error Handling

The module provides detailed error information for validation failures, including the specific path and reason for each validation error. This helps in providing meaningful feedback to users and debugging schema issues.

Index

Constants

View Source
const Name = "modular.jsonschema"

Name is the unique identifier for the jsonschema module.

Variables

This section is empty.

Functions

This section is empty.

Types

type JSONSchemaService

type JSONSchemaService interface {
	// CompileSchema compiles a JSON schema from a file path or URL.
	// The source can be a local file path, HTTP/HTTPS URL, or other URI
	// supported by the underlying JSON schema library.
	//
	// Supported source formats:
	//   - Local files: "/path/to/schema.json", "./schemas/user.json"
	//   - HTTP URLs: "https://example.com/schemas/user.json"
	//   - HTTPS URLs: "https://schemas.org/draft/2020-12/schema"
	//
	// The compiled schema is cached and can be reused for multiple validations.
	// Compilation is relatively expensive, so schemas should be compiled once
	// at application startup when possible.
	//
	// Example:
	//	schema, err := service.CompileSchema("./schemas/user.json")
	//	if err != nil {
	//	    return fmt.Errorf("failed to compile schema: %w", err)
	//	}
	CompileSchema(source string) (Schema, error)

	// ValidateBytes validates raw JSON data against a compiled schema.
	// The data parameter should contain valid JSON bytes. The method
	// unmarshals the JSON and validates it against the schema.
	//
	// This is useful when you have JSON data as a byte slice, such as
	// from HTTP request bodies, file contents, or network messages.
	//
	// Example:
	//	jsonData := []byte(`{"name": "John", "age": 30}`)
	//	err := service.ValidateBytes(schema, jsonData)
	//	if err != nil {
	//	    return fmt.Errorf("validation failed: %w", err)
	//	}
	ValidateBytes(schema Schema, data []byte) error

	// ValidateReader validates JSON from an io.Reader against a compiled schema.
	// This method reads JSON data from the reader, unmarshals it, and validates
	// against the schema. The reader is consumed entirely during validation.
	//
	// This is useful for validating streaming JSON data, HTTP request bodies,
	// or large JSON files without loading everything into memory first.
	//
	// Example:
	//	file, err := os.Open("data.json")
	//	if err != nil {
	//	    return err
	//	}
	//	defer file.Close()
	//
	//	err = service.ValidateReader(schema, file)
	//	if err != nil {
	//	    return fmt.Errorf("file validation failed: %w", err)
	//	}
	ValidateReader(schema Schema, reader io.Reader) error

	// ValidateInterface validates a Go interface{} against a compiled schema.
	// The data parameter should be a Go data structure that represents JSON data,
	// such as maps, slices, and primitive types returned by json.Unmarshal.
	//
	// This is useful when you already have unmarshaled JSON data or when
	// working with Go structs that need validation against a schema.
	//
	// Example:
	//	userData := map[string]interface{}{
	//	    "name": "Alice",
	//	    "age":  25,
	//	    "email": "alice@example.com",
	//	}
	//	err := service.ValidateInterface(schema, userData)
	//	if err != nil {
	//	    return fmt.Errorf("user data invalid: %w", err)
	//	}
	ValidateInterface(schema Schema, data interface{}) error
}

JSONSchemaService defines the operations that can be performed with JSON schemas. This service provides methods for compiling schemas from various sources and validating JSON data in different formats.

The service is thread-safe and can be used concurrently from multiple goroutines. Schemas should be compiled once and cached for reuse to avoid performance overhead.

Example usage:

// Compile schema once
schema, err := service.CompileSchema("./user-schema.json")
if err != nil {
    return err
}

// Use for multiple validations
err = service.ValidateBytes(schema, jsonData1)
err = service.ValidateBytes(schema, jsonData2)

func NewJSONSchemaService

func NewJSONSchemaService() JSONSchemaService

NewJSONSchemaService creates a new JSON schema service. The service is initialized with a fresh compiler instance and is ready to compile schemas and perform validations immediately.

The service uses sensible defaults and supports JSON Schema draft versions as configured by the underlying jsonschema library.

type Module

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

Module provides JSON Schema validation capabilities for the modular framework. It integrates JSON Schema validation into the service system and provides a simple interface for schema compilation and data validation.

The module implements the following interfaces:

  • modular.Module: Basic module lifecycle
  • modular.ServiceAware: Service dependency management

The module is stateless and thread-safe, making it suitable for concurrent validation operations in web applications and services.

func NewModule

func NewModule() *Module

NewModule creates a new instance of the JSON schema module. This is the primary constructor for the jsonschema module and should be used when registering the module with the application.

The module is stateless and creates a new schema service instance with a configured JSON schema compiler.

Example:

app.RegisterModule(jsonschema.NewModule())

func (*Module) Init

func (m *Module) Init(app modular.Application) error

Init initializes the JSON schema module. The module requires no initialization and is ready to use immediately. This method is called during application startup but performs no operations.

func (*Module) Name

func (m *Module) Name() string

Name returns the unique identifier for this module. This name is used for service registration and dependency resolution.

func (*Module) ProvidesServices

func (m *Module) ProvidesServices() []modular.ServiceProvider

ProvidesServices declares services provided by this module. The jsonschema module provides a schema validation service that can be injected into other modules for JSON data validation.

Provided services:

  • "jsonschema.service": The JSONSchemaService interface for validation operations

func (*Module) RequiresServices

func (m *Module) RequiresServices() []modular.ServiceDependency

RequiresServices declares services required by this module. The jsonschema module operates independently and requires no external services.

type Schema

type Schema interface {
	// Validate validates the given value against the JSON schema.
	// The value can be any Go data structure that represents JSON data.
	// Returns an error if validation fails, with details about the failure.
	//
	// Example:
	//	data := map[string]interface{}{"name": "John", "age": 30}
	//	err := schema.Validate(data)
	//	if err != nil {
	//	    // Handle validation error
	//	}
	Validate(value interface{}) error
}

Schema represents a compiled JSON schema. A compiled schema can be used multiple times for validation operations and is thread-safe for concurrent use. Schemas should be compiled once and reused for performance.

Jump to

Keyboard shortcuts

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