github.com/kaptinlin/jsonschema@v0.4.6/examples/constructor/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/kaptinlin/jsonschema"
     7  )
     8  
     9  func main() {
    10  	basicTypesExample()
    11  	objectSchemaExample()
    12  	schemaCompositionExample()
    13  	convenienceFunctionsExample()
    14  	setCompilerExample()
    15  }
    16  
    17  // Basic type construction
    18  func basicTypesExample() {
    19  	fmt.Println("=== Basic Types ===")
    20  
    21  	// String with validation
    22  	nameSchema := jsonschema.String(
    23  		jsonschema.MinLen(1),
    24  		jsonschema.MaxLen(50),
    25  		jsonschema.Pattern("^[a-zA-Z\\s]+$"),
    26  	)
    27  	fmt.Printf("Name validation: %t\n", nameSchema.Validate("John Doe").IsValid())
    28  
    29  	// Integer with constraints
    30  	ageSchema := jsonschema.Integer(jsonschema.Min(0), jsonschema.Max(150))
    31  	fmt.Printf("Age validation: %t\n", ageSchema.Validate(25).IsValid())
    32  
    33  	// Enum values
    34  	statusSchema := jsonschema.Enum("active", "inactive", "pending")
    35  	fmt.Printf("Status validation: %t\n", statusSchema.Validate("active").IsValid())
    36  
    37  	// Array with unique items
    38  	tagsSchema := jsonschema.Array(
    39  		jsonschema.Items(jsonschema.String()),
    40  		jsonschema.UniqueItems(true),
    41  	)
    42  	fmt.Printf("Tags validation: %t\n", tagsSchema.Validate([]interface{}{"go", "api"}).IsValid())
    43  
    44  	fmt.Println()
    45  }
    46  
    47  // Object schema with nested properties
    48  func objectSchemaExample() {
    49  	fmt.Println("=== Object Schema ===")
    50  
    51  	userSchema := jsonschema.Object(
    52  		jsonschema.Prop("name", jsonschema.String(jsonschema.MinLen(1))),
    53  		jsonschema.Prop("email", jsonschema.Email()),
    54  		jsonschema.Prop("age", jsonschema.Integer(jsonschema.Min(0))),
    55  		jsonschema.Required("name", "email"),
    56  	)
    57  
    58  	userData := map[string]interface{}{
    59  		"name":  "Alice",
    60  		"email": "alice@example.com",
    61  		"age":   30,
    62  	}
    63  
    64  	fmt.Printf("User validation: %t\n", userSchema.Validate(userData).IsValid())
    65  	fmt.Println()
    66  }
    67  
    68  // Schema composition with OneOf/AnyOf
    69  func schemaCompositionExample() {
    70  	fmt.Println("=== Schema Composition ===")
    71  
    72  	// OneOf: email or username authentication
    73  	authSchema := jsonschema.OneOf(
    74  		jsonschema.Object(
    75  			jsonschema.Prop("email", jsonschema.Email()),
    76  			jsonschema.Required("email"),
    77  		),
    78  		jsonschema.Object(
    79  			jsonschema.Prop("username", jsonschema.String()),
    80  			jsonschema.Required("username"),
    81  		),
    82  	)
    83  
    84  	emailAuth := map[string]interface{}{"email": "user@example.com"}
    85  	fmt.Printf("Email auth: %t\n", authSchema.Validate(emailAuth).IsValid())
    86  
    87  	// Conditional schema
    88  	conditionalSchema := jsonschema.If(
    89  		jsonschema.Object(jsonschema.Prop("type", jsonschema.Const("premium"))),
    90  	).Then(
    91  		jsonschema.Object(jsonschema.Required("features")),
    92  	).ToSchema()
    93  
    94  	premiumUser := map[string]interface{}{
    95  		"type":     "premium",
    96  		"features": []string{"advanced"},
    97  	}
    98  	fmt.Printf("Conditional: %t\n", conditionalSchema.Validate(premiumUser).IsValid())
    99  	fmt.Println()
   100  }
   101  
   102  // Convenience functions for common formats
   103  func convenienceFunctionsExample() {
   104  	fmt.Println("=== Convenience Functions ===")
   105  
   106  	// Test individual convenience functions
   107  	fmt.Printf("UUID: %t\n", jsonschema.UUID().Validate("550e8400-e29b-41d4-a716-446655440000").IsValid())
   108  	fmt.Printf("Email: %t\n", jsonschema.Email().Validate("test@example.com").IsValid())
   109  	fmt.Printf("DateTime: %t\n", jsonschema.DateTime().Validate("2023-12-01T10:30:00Z").IsValid())
   110  	fmt.Printf("PositiveInt: %t\n", jsonschema.PositiveInt().Validate(5).IsValid())
   111  	fmt.Println()
   112  }
   113  
   114  // SetCompiler example for dynamic defaults
   115  func setCompilerExample() {
   116  	fmt.Println("=== SetCompiler with Dynamic Defaults ===")
   117  
   118  	// Create custom compiler with dynamic functions
   119  	compiler := jsonschema.NewCompiler()
   120  	compiler.RegisterDefaultFunc("now", jsonschema.DefaultNowFunc)
   121  
   122  	// Create schema and set custom compiler
   123  	userSchema := jsonschema.Object(
   124  		jsonschema.Prop("id", jsonschema.String(jsonschema.Default("user_123"))),
   125  		jsonschema.Prop("createdAt", jsonschema.String(jsonschema.Default("now()"))),
   126  		jsonschema.Prop("status", jsonschema.String(jsonschema.Default("active"))),
   127  	).SetCompiler(compiler)
   128  
   129  	// Test with empty input
   130  	var result map[string]interface{}
   131  	err := userSchema.Unmarshal(&result, map[string]interface{}{})
   132  	if err != nil {
   133  		fmt.Printf("Error: %v\n", err)
   134  		return
   135  	}
   136  
   137  	fmt.Println("Generated defaults:")
   138  	for key, value := range result {
   139  		fmt.Printf("  %s: %v\n", key, value)
   140  	}
   141  }