-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathexample_http_test.go
73 lines (62 loc) · 1.48 KB
/
example_http_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package jsonschema_test
import (
"crypto/tls"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/santhosh-tekuri/jsonschema/v6"
)
type HTTPURLLoader http.Client
func (l *HTTPURLLoader) Load(url string) (any, error) {
client := (*http.Client)(l)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
return nil, fmt.Errorf("%s returned status code %d", url, resp.StatusCode)
}
defer resp.Body.Close()
return jsonschema.UnmarshalJSON(resp.Body)
}
func newHTTPURLLoader(insecure bool) *HTTPURLLoader {
httpLoader := HTTPURLLoader(http.Client{
Timeout: 15 * time.Second,
})
if insecure {
httpLoader.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
return &httpLoader
}
func Example_fromHTTPS() {
schemaURL := "https://raw.githubusercontent.com/santhosh-tekuri/boon/main/tests/examples/schema.json"
instanceFile := "./testdata/examples/instance.json"
loader := jsonschema.SchemeURLLoader{
"file": jsonschema.FileLoader{},
"http": newHTTPURLLoader(false),
"https": newHTTPURLLoader(false),
}
c := jsonschema.NewCompiler()
c.UseLoader(loader)
sch, err := c.Compile(schemaURL)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(instanceFile)
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(f)
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
// Output:
// valid: true
}