File: doc_test.go

package info (click to toggle)
golang-github-go-openapi-loads 0.23.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,228 kB
  • sloc: makefile: 4
file content (62 lines) | stat: -rw-r--r-- 1,407 bytes parent folder | download
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
package loads_test

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"github.com/go-openapi/loads"
	"github.com/go-openapi/swag/loading"
)

// Example with default loaders defined at the package level
func ExampleSpec_file() {

	path := "fixtures/yaml/swagger/spec.yml"
	doc, err := loads.Spec(path)
	if err != nil {
		fmt.Println("Could not load this spec")
		return
	}

	fmt.Printf("Spec loaded: %q\n", doc.Host())

	// Output: Spec loaded: "api.example.com"
}

// Example with custom loaders passed as options
func ExampleLoaderOption() {
	path := "fixtures/yaml/swagger/spec.yml"

	// a simpler version of loads.JSONDoc
	jsonLoader := loads.NewDocLoaderWithMatch(
		func(pth string, _ ...loading.Option) (json.RawMessage, error) {
			buf, err := os.ReadFile(pth)
			return json.RawMessage(buf), err
		},
		func(pth string) bool {
			return filepath.Ext(pth) == ".json"
		},
	)

	// equivalent to the default loader at the package level, which does:
	//
	//   loads.AddLoader(loading.YAMLMatcher, loading.YAMLDoc)
	yamlLoader := loads.NewDocLoaderWithMatch(
		loading.YAMLDoc,
		func(pth string) bool {
			return filepath.Ext(pth) == ".yml"
		},
	)

	doc, err := loads.Spec(path, loads.WithDocLoaderMatches(jsonLoader, yamlLoader))
	if err != nil {
		fmt.Println("Could not load this spec")
		return
	}

	fmt.Printf("Spec loaded: %q\n", doc.Host())

	// Output: Spec loaded: "api.example.com"
}