OPEN SWAG GO
Features

Example Generator

Open-swag-go can generate realistic example values for your API schemas automatically. The examples package uses a combination of struct tags, field name heuristics, and a built-in Faker to produce meaningful sample data without manual effort.

How It Works

When a struct field has an example tag, that value is used directly. When it doesn't, the generator inspects the field name and type to produce a sensible default. A field named email gets an email address, phone gets a phone number, and so on.

auto_examples.go
type User struct {
	Name      string `json:"name"`
	Email     string `json:"email"`
	Phone     string `json:"phone"`
	Age       int    `json:"age"`
	CreatedAt string `json:"created_at"`
}
// Generated example:
// {
//   "name": "John Smith",
//   "email": "john.smith@example.com",
//   "phone": "+1-555-0100",
//   "age": 30,
//   "created_at": "2024-01-15T09:30:00Z"
// }

Generator

The Generator struct controls how examples are produced:

generator_type.go
import "github.com/gopackx/open-swag-go/pkg/examples"
 
gen := examples.New(examples.Config{
	UseFaker: true, // Use the Faker for realistic values
})
 
example := gen.Generate(User{})         // populated value
asMap := gen.GenerateJSON(User{})       // map[string]interface{}

Config options

FieldTypeDescription
UseFakerboolUse the Faker to produce realistic values
TypeExamplesmap[string]interface{}Per-format default examples (defaults to DefaultTypeExamples() when nil)

Faker

The Faker provides realistic values based on field names. It matches common naming patterns and returns appropriate sample data.

faker_usage.go
faker := examples.NewFaker()
 
faker.Name()      // "Alice Johnson"
faker.Email()     // "alice.johnson@example.com"
faker.Phone()     // "+1-555-0142"
faker.UUID()      // "550e8400-e29b-41d4-a716-446655440000"
faker.URL()       // "https://example.com/resource"
faker.IPv4()      // "192.168.1.42"
faker.Sentence()  // "The quick brown fox jumps over the lazy dog."

Smart Field Name Heuristics

The generator matches field names (case-insensitive) to categories and picks an appropriate example value:

Field Name PatternExample Value
name, username, full_name"John Smith"
email, mail"john.smith@example.com"
phone, mobile, tel"+1-555-0100"
url, website, link"https://example.com"
address, street"123 Main St"
city"Springfield"
state"IL"
zip, postal_code"62701"
country"US"
id, uuid"550e8400-e29b-41d4-..."
created_at, updated_at"2024-01-15T09:30:00Z"
price, amount, cost29.99
description, bio, summary"A brief description."
password, secret"********"
token"eyJhbGciOiJIUzI1NiIs..."
ip, ip_address"192.168.1.1"

When no heuristic matches, the generator falls back to type-based defaults ("" for strings, 0 for numbers, false for booleans).

Explicit Examples with Tags

Struct tags always take priority over heuristics. Use the example tag for precise control:

explicit_examples.go
type Product struct {
	Name  string  `json:"name"  example:"Wireless Headphones"`
	Price float64 `json:"price" example:"79.99"`
	SKU   string  `json:"sku"   example:"WH-1000XM5"`
}

You can mix explicit tags and auto-generation. Fields with example tags use the tag value; fields without tags use heuristics or defaults.

Type-Aware Example Coercion (v1.1.0+)

Example tag values are now automatically coerced to the correct type. Previously, example:"42" on an int64 field would appear as a string "42" in the OpenAPI spec. Now it's correctly output as the integer 42.

typed_examples.go
type Product struct {
	ID       int64   `json:"id"       example:"42"`      // → 42 (integer)
	Price    float64 `json:"price"    example:"9.99"`     // → 9.99 (number)
	Active   bool    `json:"active"   example:"true"`     // → true (boolean)
	Name     string  `json:"name"     example:"Widget"`   // → "Widget" (string)
}

This coercion is applied everywhere examples appear: schema generation, request body examples, and the OpenAPI spec output.

Request Body Auto-Examples (v1.1.0+)

Request body schemas now automatically include a generated example field built from struct field tags and type defaults. You no longer need to manually craft example payloads — they're derived from your struct definitions.

auto_body_example.go
type CreateOrderRequest struct {
	ProductID int64  `json:"product_id" example:"7"`
	Quantity  int    `json:"quantity"   example:"2"`
	Note      string `json:"note"       example:"Gift wrap please"`
}
 
// The generated request body schema automatically includes:
// "example": {"product_id": 7, "quantity": 2, "note": "Gift wrap please"}

Full Example

A complete setup with the example generator and an endpoint:

full_example_gen.go
package main
 
import (
	"net/http"
 
	openswag "github.com/gopackx/open-swag-go"
	"github.com/gopackx/open-swag-go/pkg/examples"
	adapter "github.com/gopackx/open-swag-go/adapters/nethttp"
)
 
type CreateUserRequest struct {
	Name  string `json:"name"`
	Email string `json:"email"`
	Phone string `json:"phone"`
	Age   int    `json:"age" example:"25"`
}
 
type UserResponse struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Email     string `json:"email"`
	CreatedAt string `json:"created_at"`
}
 
func main() {
	// Generate example values standalone.
	gen := examples.New(examples.Config{UseFaker: true})
	_ = gen.GenerateJSON(CreateUserRequest{})
 
	docs := openswag.New(openswag.Config{
		Info: openswag.Info{
			Title:   "User API",
			Version: "1.0.0",
		},
	})
 
	docs.Add(openswag.Endpoint{
		Method:  "POST",
		Path:    "/users",
		Summary: "Create a user",
		Tags:    []string{"Users"},
		RequestBody: &openswag.RequestBody{
			ContentType: "application/json",
			Required:    true,
			Schema:      CreateUserRequest{},
		},
		Responses: openswag.Responses{
			201: {Description: "User created", Schema: UserResponse{}},
		},
	})
 
	mux := http.NewServeMux()
	adapter.Mount(mux, docs, "/docs")
 
	http.ListenAndServe(":8080", mux)
}