OPEN SWAG GO
Features

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: BuildSpec does not call it. Examples in the generated openapi.json come only from example:"..." tags (see Schema Generation), and fields without one have no example (v1.1.1+).

Generator

generator.go
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 struct

Config options

FieldTypeDescription
TypeExamplesmap[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:

type_examples.go
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:

  1. example tag, 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.
  2. format tag, looked up in TypeExamples.
  3. format=... inside the swagger tag, looked up in TypeExamples.
  4. Field name heuristics (below).
  5. Type default.
auto_examples.go
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 nameExample 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 age25
contains count or total100
contains price or amount99.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 typeExample value
string"string"
integers42
floats3.14
booltrue
time.Time"2024-01-15T10:30:00Z"
[]Ta one-element array with T's example
map[K]V{"key": "value"}
nested structan object built with the same rules
*TT's example
anything else (interface{}, …)nil

Full Example

full_example_gen.go
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).