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.
- π 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.
Before you begin, ensure you have the following installed:
- Go: v1.21.x or higher (Tested with v1.23+)
- Git: For version control
go get github.com/vihuvac/go-openapi-validatorpackage 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)))
}.
βββ 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
| 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 |
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.outContributions are welcome! Check out the Contribution Guide to get started.
This project is licensed under the MIT License. See the LICENSE file for more details.
