github.com/kaptinlin/jsonschema@v0.4.6/examples/struct-validation/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/kaptinlin/jsonschema"
     8  )
     9  
    10  // User represents a user in our system
    11  type User struct {
    12  	Name  string `json:"name"`
    13  	Age   int    `json:"age"`
    14  	Email string `json:"email,omitempty"`
    15  }
    16  
    17  func main() {
    18  	// Compile schema
    19  	compiler := jsonschema.NewCompiler()
    20  	schema, err := compiler.Compile([]byte(`{
    21  		"type": "object",
    22  		"properties": {
    23  			"name": {"type": "string", "minLength": 1},
    24  			"age": {"type": "integer", "minimum": 18},
    25  			"email": {"type": "string", "format": "email"}
    26  		},
    27  		"required": ["name", "age"]
    28  	}`))
    29  	if err != nil {
    30  		log.Fatal(err)
    31  	}
    32  
    33  	// Valid struct
    34  	validUser := User{
    35  		Name:  "Alice",
    36  		Age:   25,
    37  		Email: "alice@example.com",
    38  	}
    39  	if schema.ValidateStruct(validUser).IsValid() {
    40  		fmt.Println("✅ Valid struct passed")
    41  	}
    42  
    43  	// Invalid struct
    44  	invalidUser := User{
    45  		Name: "Bob",
    46  		Age:  16, // under 18
    47  	}
    48  	result := schema.ValidateStruct(invalidUser)
    49  	if !result.IsValid() {
    50  		fmt.Println("❌ Invalid struct failed:")
    51  		for field, errors := range result.Errors {
    52  			fmt.Printf("  - %s: %v\n", field, errors)
    53  		}
    54  	}
    55  
    56  	// Alternative: use general Validate method
    57  	fmt.Println("\nUsing general Validate method:")
    58  	if schema.Validate(validUser).IsValid() {
    59  		fmt.Println("✅ Auto-detected struct validation passed")
    60  	}
    61  }