Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do you load schemas from memory rather than URLs? #89

Closed
insano10 opened this issue Oct 20, 2022 · 2 comments
Closed

How do you load schemas from memory rather than URLs? #89

insano10 opened this issue Oct 20, 2022 · 2 comments

Comments

@insano10
Copy link

I have an API that takes a JSON schema and a document to validate against that schema. This is so schemas can be created dynamically. In order to compile that schema into a Schema struct I've had to write a custom loader to wrap reading the bytes from the request. Is there a more elegant way to do this with this library? I don't want to be registering a new loader for each request that could have a separate schema.

// error handling removed for clarity

type ValidationRequest struct {
	Schema   interface{}
	Document interface{}
}

body := ValidationRequest{}
web.Unmarshal(request, &body)

schemaBytes, err := json.Marshal(body.Schema)

jsonschema.Loaders["memory"] = func(_ string) (io.ReadCloser, error) {
	return ioutil.NopCloser(bytes.NewReader(schemaBytes)), nil
}

schema, err := jsonschema.Compile("memory:///foo")


err = schema.Validate(body.Document)

@santhosh-tekuri
Copy link
Owner

since multiple requests might be coming concurrently, updating jsonschema.Loaders global variable will cause data race.

one solution is to use Compiler.AddResource:

c := jsonschema.NewCompiler()
if err := c.AddResource("schema.json", bytes.NewReader(schemaBytes)); err!=nil {
    panic(err)
}
schema, err := c.Compile("schema.json")

another solution is to use Compiler.LoadURL:

c := jsonschema.NewCompiler()
c.LoadURL = func(s string) (io.ReadCloser, error) {
    if s == "memory:///schema.json" {
        return bytes.NewReader(schemaBytes), nil
    }
    return jsonschema.LoadURL(s) // delegate to default impl
}
schema, err := c.Compile("memory:///schema.json")

@insano10
Copy link
Author

Thank you for your suggestions that is helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants