基于Go语言实现OpenAPI规范验证CLI工具的最小示例求助
Minimal Example: Validate OpenAPI Specs with go-openapi/validate in Go
I totally feel your pain—documentation for go-openapi/validate is pretty sparse when you're just trying to get up and running. Here's a stripped-down, working CLI tool example that reads an OpenAPI spec file (YAML or JSON) and runs full schema validation, with clear error output.
Step 1: Set Up Dependencies
First, initialize your Go module and install the required packages:
go mod init openapi-spec-validator go get github.com/go-openapi/validate github.com/go-openapi/loads
Step 2: The Minimal Validation Code
Create a main.go file with this code:
package main import ( "fmt" "os" "github.com/go-openapi/loads" "github.com/go-openapi/validate" ) func main() { // Check for correct CLI argument count if len(os.Args) != 2 { fmt.Printf("Usage: %s <path-to-openapi-spec>\n", os.Args[0]) os.Exit(1) } specFilePath := os.Args[1] // Load and parse the OpenAPI spec (supports YAML and JSON) loadedSpec, err := loads.Spec(specFilePath) if err != nil { fmt.Printf("Error loading spec file: %v\n", err) os.Exit(1) } // Run validation against the spec schema validationErrors := validate.Spec(loadedSpec.Schema(), nil) if validationErrors != nil { fmt.Println("❌ Validation failed with errors:") for _, err := range validationErrors.Errors { fmt.Printf("- %s (location: %s)\n", err.Error(), err.Name) } os.Exit(1) } fmt.Println("✅ OpenAPI spec is valid!") }
How It Works
Let’s break down the key parts:
- Loading the Spec:
loads.Spec()handles both YAML and JSON formats, parses the file into a structured OpenAPI schema object, and catches basic parsing errors like invalid syntax. - Validation:
validate.Spec()checks the parsed schema against official OpenAPI rules (e.g., required fields, valid data types, correct path formats). Thenilargument uses default validation settings—ideal for core spec validity checks. - Error Handling: Validation errors are returned as a collection, which we loop through to print human-readable messages including where the error occurs in the spec.
Run the Tool
Build and execute the CLI:
go build -o openapi-validator ./openapi-validator ./path/to/your/openapi.yaml
This will immediately flag issues like missing required fields, invalid parameter types, or malformed OpenAPI version declarations.
内容的提问来源于stack exchange,提问作者Matias Barrios
相关产品推荐
相关产品推荐

