santhosh-tekuri / jsonschema

JSONSchema (draft 2020-12, draft 2019-09, draft-7, draft-6, draft-4) Validation using Go
Apache License 2.0
957 stars 98 forks source link

Feature: Auto-load URI references #92

Closed decentralgabe closed 2 years ago

decentralgabe commented 2 years ago

Problem

I'm attempting to validate a piece of JSON against this schema which references a few others schemas.

Code is a bit simplified for an example.


const presentationExchangeSchema = "schema.json"

func ValidatePresentationExchange(inputJSON map[string]interface{}) error {
        jsonSchema, err := jsonschema.CompileString("test-url.json", presentationExchangeSchema)
    if err != nil {
        return err
    }
    return jsonSchema.Validate(inputJSON)
}

this returns

 jsonschema file:///.../.../schema.json compilation failed: no Loader found for http://identity.foundation/claim-format-registry/schemas/presentation-definition-claim-format-designations.json"

I am assuming the fix is to add each $ref into the Loaders object.

Request

My request is for the library to handle this, attempting to resolve the schema at the URL (perhaps a default HTTP loader). Needing to pre-process each schema for its external URI references before validation can be difficult.

Reference

I am attempting to migrate our open source projects to this library from gojsonschema because it supports the latest drafts. This is a feature that the old library supports: https://github.com/xeipuuv/gojsonschema/blob/master/schemaPool.go#L48

decentralgabe commented 2 years ago

Note: I see in the readme it says full support of remote references so perhaps this is a configuration error on my part and this functionality already exists?

decentralgabe commented 2 years ago

Disregard, I figured it out. Sorry 😄

func init() {
    jsonschema.Loaders["http"] = httploader.Load
    jsonschema.Loaders["https"] = httploader.Load
}
santhosh-tekuri commented 2 years ago

you don't need to explicitly add it to jsonschema.Loaders. simply do:

import _ "github.com/santhosh-tekuri/jsonschema/v5/httploader"

it automatically adds them to jsonschema.Loaders. this is already documented in README page.

also would like to mention that httploader package uses http.DefaultClient which has no timeouts configured by default. so you may want to configure timeouts and assign it to httploader.Client