Example Generator
pkg/examples builds an example value from a Go type: it walks the struct fields and fills each one from its example tag, its format, its field name, or its type. Use it for fixtures, tests, or example payloads you want to publish yourself.
import "github.com/gopackx/open-swag-go/pkg/examples"The generator is standalone:
BuildSpecdoes not call it. Examples in the generatedopenapi.jsoncome only fromexample:"..."tags (see Schema Generation), and fields without one have no example (v1.1.1+).
Generator
gen := examples.New(examples.Config{}) // nil TypeExamples = DefaultTypeExamples()
example := gen.Generate(User{}) // interface{}: map[string]interface{} for a struct
asMap := gen.GenerateJSON(User{}) // map[string]interface{}, or nil if the value is not a structConfig options
| Field | Type | Description |
|---|---|---|
TypeExamples | map[string]interface{} | Example value per format name ("email", "uuid", …). nil means DefaultTypeExamples() |
DefaultTypeExamples() covers uuid, email, uri, url, hostname, ipv4, ipv6, date, date-time, time, password, byte and binary. Pass your own map to change or extend them:
custom := examples.DefaultTypeExamples()
custom["email"] = "dev@acme.test"
custom["sku"] = "WH-1000XM5"
gen := examples.New(examples.Config{TypeExamples: custom})How Each Field Is Filled
For every exported struct field (the name is the json tag name, or the Go field name; json:"-" fields are skipped), the first rule that applies wins:
exampletag, converted to the field type: integers, unsigned integers, floats and booleans are parsed, slices and maps are parsed as JSON. A value that does not parse stays a string.formattag, looked up inTypeExamples.format=...inside theswaggertag, looked up inTypeExamples.- Field name heuristics (below).
- Type default.
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Website string `json:"website" format:"uri"`
Age int `json:"age" example:"30"`
CreatedAt string `json:"created_at"`
}
// gen.Generate(User{}):
// {
// "id": "550e8400-e29b-41d4-a716-446655440000",
// "name": "John Doe",
// "email": "user@example.com",
// "website": "https://example.com",
// "age": 30,
// "created_at": "2024-01-15T10:30:00Z"
// }Field name heuristics
The JSON field name is lowercased and checked against these patterns in order; the first match wins:
| Field name | Example value |
|---|---|
contains email | "user@example.com" |
contains phone | "+1-555-123-4567" |
id, or ends in id / _id | "550e8400-e29b-41d4-a716-446655440000" for strings, 1 otherwise |
contains name | "John Doe" |
contains url or link | "https://example.com" |
contains password | "********" |
contains token | "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." |
contains created or updated | "2024-01-15T10:30:00Z" |
contains date | "2024-01-15" |
contains time | "10:30:00" |
contains age | 25 |
contains count or total | 100 |
contains price or amount | 99.99 |
contains description | "A sample description" |
contains title | "Sample Title" |
contains address | "123 Main St, City, Country" |
contains status | "active" |
contains type | "default" |
Type defaults
| Go type | Example value |
|---|---|
string | "string" |
| integers | 42 |
| floats | 3.14 |
bool | true |
time.Time | "2024-01-15T10:30:00Z" |
[]T | a one-element array with T's example |
map[K]V | {"key": "value"} |
| nested struct | an object built with the same rules |
*T | T's example |
anything else (interface{}, …) | nil |
Full Example
package main
import (
"encoding/json"
"fmt"
"github.com/gopackx/open-swag-go/pkg/examples"
)
type CreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
Phone string `json:"phone"`
Age int `json:"age" example:"25"`
}
func main() {
gen := examples.New(examples.Config{})
payload := gen.GenerateJSON(CreateUserRequest{})
data, _ := json.MarshalIndent(payload, "", " ")
fmt.Println(string(data))
// {
// "age": 25,
// "email": "user@example.com",
// "name": "John Doe",
// "phone": "+1-555-123-4567"
// }
}See the Examples Package reference for the full API. Before v1.3.0 the package also contained a fake-data helper, an example template registry and a matching Config switch. None of them were used by the generator or the docs UI, and they were removed in v1.3.0 (see the Changelog).