openapi_validator

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 11 Imported by: 0

README ยถ

Go OpenAPI Validator Logo

Go OpenAPI Validator

A framework-agnostic OpenAPI v3 validator for Go, designed for performance and reliability.

Go Version License OpenAPI Version
Tests Status Coverage
Security Policy Code of Conduct PRs Welcome


๐Ÿ“– Overview

Go OpenAPI Validator is a high-performance, framework-agnostic library for validating HTTP requests and responses against OpenAPI v3 specifications. Inspired by express-openapi-validator, it provides a robust middleware layer that ensures your API remains consistent with its documentation.

We focus on minimalism and reliability, with zero external testing dependencies and a lean footprint.

โœจ Key Features

  • ๐Ÿš€ Framework Agnostic: Native support for net/http, Gorilla Mux, and Gin.
  • ๐Ÿ›ก๏ธ Request Validation: Automatic validation of request bodies, query parameters, and headers.
  • โœ… Response Validation: Optional outgoing response validation to catch implementation errors.
  • ๐Ÿ“„ Swagger UI: Built-in, zero-config Swagger UI integration served at /docs.
  • ๐Ÿงช Professional Grade: Comprehensive test suite using only the Go standard library.
  • โš™๏ธ Highly Configurable: Custom error encoders, router selection, and more.

๐Ÿ› ๏ธ System Requirements

Before you begin, ensure you have the following installed:

  • Go: v1.21.x or higher (Tested with v1.23+)
  • Git: For version control

๐Ÿš€ Getting Started

1. Installation

go get github.com/vihuvac/go-openapi-validator

2. Usage Examples

Standard Library (net/http)
package main

import (
	"log"
	"net/http"
	"github.com/getkin/kin-openapi/routers/legacy"
	validator "github.com/vihuvac/go-openapi-validator"
)

func main() {
	v, err := validator.New("openapi.yaml")
	if err != nil {
		log.Fatal(err)
	}

	// For net/http, use the legacy router
	r, _ := legacy.NewRouter(v.Swagger)
	validator.WithRouter(r)(v.Options)

	mux := http.NewServeMux()
	v.HandleSwaggerUI(mux)

	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"message": "Hello World"}`))
	})

	log.Fatal(http.ListenAndServe(":8080", v.Middleware(mux)))
}

๐Ÿ“‚ Project Structure

.
โ”œโ”€โ”€ docs/             # Documentation and assets
โ”œโ”€โ”€ examples/         # Router-specific implementation examples
โ”‚   โ”œโ”€โ”€ gin/          # Gin-gonic integration
โ”‚   โ”œโ”€โ”€ gorilla/      # Gorilla Mux integration
โ”‚   โ””โ”€โ”€ standard/     # Standard net/http integration
โ”œโ”€โ”€ swagger-ui/       # Embedded Swagger UI assets
โ”œโ”€โ”€ errors.go         # Custom error handling and encoders
โ”œโ”€โ”€ options.go        # Configuration options (Functional options pattern)
โ”œโ”€โ”€ swagger.go        # Swagger UI serving logic
โ””โ”€โ”€ validator.go      # Core validation middleware

โš™๏ธ Configuration

Option Description Default
WithValidateRequests(bool) Enable/Disable request validation true
WithValidateResponses(bool) Enable/Disable response validation false
WithSwaggerUIPath(string) Change Swagger UI base path /docs
WithErrorEncoder(ErrorEncoder) Custom error response format DefaultErrorEncoder
WithRouter(routers.Router) Set a custom OpenAPI router gorillamux.NewRouter

๐Ÿงช Running Tests

Maintain code quality by running the comprehensive test suite:

# Run all unit tests
go test ./...

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

๐Ÿค Contributing

Contributions are welcome! Check out the Contribution Guide to get started.

๐Ÿ“„ License

This project is licensed under the MIT License. See the LICENSE file for more details.

Additional Resources

Project

Tools

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

This section is empty.

Functions ยถ

func DefaultErrorEncoder ยถ

func DefaultErrorEncoder(w http.ResponseWriter, r *http.Request, err error)

DefaultErrorEncoder is a built-in implementation of ErrorEncoder. It sends a JSON response with a 400 Bad Request status code.

Types ยถ

type ErrorEncoder ยถ

type ErrorEncoder func(w http.ResponseWriter, r *http.Request, err error)

ErrorEncoder is a function type used to encode validation errors into an HTTP response.

type Option ยถ

type Option func(*Options)

Option is a function type used to configure the Options struct.

func WithErrorEncoder ยถ

func WithErrorEncoder(encoder ErrorEncoder) Option

WithErrorEncoder returns an Option that sets a custom error encoder.

func WithRouter ยถ

func WithRouter(router routers.Router) Option

WithRouter returns an Option that sets a custom router.

func WithSwaggerUIPath ยถ

func WithSwaggerUIPath(path string) Option

WithSwaggerUIPath returns an Option that sets the URL path for the Swagger UI.

func WithValidateRequests ยถ

func WithValidateRequests(validate bool) Option

WithValidateRequests returns an Option that enables or disables request validation.

func WithValidateResponses ยถ

func WithValidateResponses(validate bool) Option

WithValidateResponses returns an Option that enables or disables response validation.

type Options ยถ

type Options struct {
	// ValidateRequests specifies whether incoming requests should be validated against the spec.
	ValidateRequests bool
	// ValidateResponses specifies whether outgoing responses should be validated against the spec.
	ValidateResponses bool
	// SwaggerUIPath is the URL path where Swagger UI will be served.
	SwaggerUIPath string
	// ErrorEncoder is used to format and send validation error responses.
	ErrorEncoder ErrorEncoder
	// Router is used for matching requests to OpenAPI paths.
	Router routers.Router
}

Options contains the configuration for the OpenAPI validator.

func DefaultOptions ยถ

func DefaultOptions() *Options

DefaultOptions returns the default configuration for the validator.

type Registrar ยถ

type Registrar interface {
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}

Registrar is an interface that matches both http.ServeMux and gorilla/mux.Router.

type ValidationError ยถ

type ValidationError struct {
	Message string   `json:"message"`
	Errors  []string `json:"errors,omitempty"`
}

ValidationError represents a failed validation attempt. It includes a top-level message and an optional list of detailed error strings.

func (*ValidationError) Error ยถ

func (e *ValidationError) Error() string

Error implements the error interface for ValidationError.

type Validator ยถ

type Validator struct {
	// Options holds the configuration for the validator.
	Options *Options
	// Swagger is the parsed OpenAPI 3 specification.
	Swagger *openapi3.T
}

Validator is the core component that manages OpenAPI validation and Swagger UI.

func New ยถ

func New(specPath string, opts ...Option) (*Validator, error)

New creates a new Validator instance from an OpenAPI spec file and optional configuration. It parses and validates the spec, and initializes the router.

func (*Validator) HandleSwaggerUI ยถ

func (v *Validator) HandleSwaggerUI(mux Registrar)

HandleSwaggerUI registers the necessary routes to serve the Swagger UI and the OpenAPI spec.

func (*Validator) Middleware ยถ

func (v *Validator) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that validates incoming requests and/or outgoing responses.

func (*Validator) SwaggerUIHandler ยถ

func (v *Validator) SwaggerUIHandler() http.Handler

SwaggerUIHandler returns an http.Handler that serves the Swagger UI and the OpenAPI spec.

Directories ยถ

Path Synopsis
examples
gin command
gorilla command
standard command

Jump to

Keyboard shortcuts

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