Debian Codegraph @

helpers/url_loader.go

raw
1 // Copyright 2023-2024 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // https://pb33f.io
3
4 package helpers
5
6 import (
7 "crypto/tls"
8 "fmt"
9 "net/http"
10 "time"
11
12 "github.com/santhosh-tekuri/jsonschema/v6"
13 )
14
15 // HTTPURLLoader is a type that implements the Loader interface for loading schemas from HTTP URLs.
16 // this change was made in jsonschema v6. The httploader package was removed and the HTTPURLLoader
17 // type was introduced.
18 // https://github.com/santhosh-tekuri/jsonschema/blob/boon/example_http_test.go
19 // TODO: make all this stuff configurable, right now it's all hard wired and not very flexible.
20 //
21 // use interfaces and abstractions on all this.
22 type HTTPURLLoader http.Client
23
24 func (l *HTTPURLLoader) Load(url string) (any, error) {
25 client := (*http.Client)(l)
26 resp, err := client.Get(url)
27 if err != nil {
28 return nil, err
29 }
30 if resp.StatusCode != http.StatusOK {
31 _ = resp.Body.Close()
32 return nil, fmt.Errorf("%s returned status code %d", url, resp.StatusCode)
33 }
34 defer resp.Body.Close()
35
36 return jsonschema.UnmarshalJSON(resp.Body)
37 }
38
39 func NewHTTPURLLoader(insecure bool) *HTTPURLLoader {
40 httpLoader := HTTPURLLoader(http.Client{
41 Timeout: 15 * time.Second,
42 })
43 if insecure {
44 httpLoader.Transport = &http.Transport{
45 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
46 }
47 }
48 return &httpLoader
49 }
50
51 func NewCompilerLoader() jsonschema.SchemeURLLoader {
52 return jsonschema.SchemeURLLoader{
53 "file": jsonschema.FileLoader{},
54 "http": NewHTTPURLLoader(false),
55 "https": NewHTTPURLLoader(false),
56 }
57 }