You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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). The nil argument 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:48:57