xeipuuv/gojsonschema

major api improvement

amills-vibeirl opened this issue · 2 comments

the main workflow looks like this right now:


package main

import (
    "encoding/json"
    "fmt"
    "github.com/xeipuuv/gojsonschema"
    "log"
)

func main() {

    type Person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    person := Person{Name: "John Doe", Age: 30}

    personJSON, err := json.Marshal(person)
    if err != nil {
        log.Fatal(err)
    }

    schemaLoader := gojsonschema.NewReferenceLoader("file:///path/to/your/schema.json")
    documentLoader := gojsonschema.NewBytesLoader(personJSON)

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    if err != nil {
        log.Fatal(err)
    }

    if result.Valid() {
        fmt.Println("The document is valid")
    } else {
        fmt.Println("The document is not valid. see errors :")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}

but it should look like this instead:


func main() {

    type Person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    person := Person{Name: "John Doe", Age: 30}
    schema := gojsonschema.NewReferenceLoader("file:///path/to/your/schema.json")

    result, err := gojsonschema.Validate(schema, person)
    if err != nil {
        log.Fatal(err)
    }

    if result.Valid() {
        fmt.Println("The document is valid")
    } else {
        fmt.Println("The document is not valid. see errors :")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}

  1. at the very least the API should convert to JSON for us
  2. you should accept the struct with struct tags, iterate over that instead of comparing json to json-schema

If you are accepting JSON and than Unmarshaling it back to a struct, that's a waste of resources. But I would have to inspect the implementation.