...

Source file src/github.com/go-openapi/loads/doc_test.go

Documentation: github.com/go-openapi/loads

     1  package loads_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/go-openapi/loads"
    10  	"github.com/go-openapi/swag"
    11  )
    12  
    13  func ExampleSpec() {
    14  	// Example with default loaders defined at the package level
    15  
    16  	path := "fixtures/yaml/swagger/spec.yml"
    17  	doc, err := loads.Spec(path)
    18  	if err != nil {
    19  		fmt.Println("Could not load this spec")
    20  		return
    21  	}
    22  
    23  	fmt.Printf("Spec loaded: %q\n", doc.Host())
    24  
    25  	// Output: Spec loaded: "api.example.com"
    26  }
    27  
    28  func ExampleLoaderOption() {
    29  	// Example with custom loaders passed as options
    30  
    31  	path := "fixtures/yaml/swagger/spec.yml"
    32  
    33  	// a simpler version of loads.JSONDoc
    34  	jsonLoader := loads.NewDocLoaderWithMatch(
    35  		func(pth string) (json.RawMessage, error) {
    36  			buf, err := os.ReadFile(pth)
    37  			return json.RawMessage(buf), err
    38  		},
    39  		func(pth string) bool {
    40  			return filepath.Ext(pth) == ".json"
    41  		},
    42  	)
    43  
    44  	// equivalent to the default loader at the package level, which does:
    45  	//
    46  	//   loads.AddLoader(swag.YAMLMatcher, swag.YAMLDoc)
    47  	yamlLoader := loads.NewDocLoaderWithMatch(
    48  		swag.YAMLDoc,
    49  		func(pth string) bool {
    50  			return filepath.Ext(pth) == ".yml"
    51  		},
    52  	)
    53  
    54  	doc, err := loads.Spec(path, loads.WithDocLoaderMatches(jsonLoader, yamlLoader))
    55  	if err != nil {
    56  		fmt.Println("Could not load this spec")
    57  		return
    58  	}
    59  
    60  	fmt.Printf("Spec loaded: %q\n", doc.Host())
    61  
    62  	// Output: Spec loaded: "api.example.com"
    63  }
    64  

View as plain text