loads

package module
v0.23.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2026 License: Apache-2.0 Imports: 12 Imported by: 3,589

README

Loads OAI specs

Tests Coverage CI vuln scan CodeQL

Release Go Report Card CodeFactor Grade License

GoDoc Discord Channel go version Top language Commits since latest release


Loads OAI v2 API specification documents from local or remote locations.

Supports JSON and YAML documents.

Announcements

  • 2025-12-19 : new community chat on discord
    • a new discord community channel is available to be notified of changes and support users
    • our venerable Slack channel remains open, and will be eventually discontinued on 2026-03-31

You may join the discord community by clicking the invite link on the discord badge (also above). Discord Channel

Or join our Slack channel: Slack Channelslack-badge

Status

API is stable.

Import this library in your project

go get github.com/go-openapi/loads

Basic usage

  import (
	  "github.com/go-openapi/loads"
  )

  ...

	// loads a YAML spec from a http file
	doc, err := loads.Spec(ts.URL)
  
  ...

  // retrieves the object model for the API specification
  spec := doc.Spec()

  ...

See also the provided examples.

Change log

See https://github.com/go-openapi/loads/releases

Licensing

This library ships under the SPDX-License-Identifier: Apache-2.0.

Other documentation

Cutting a new release

Maintainers can cut a new release by either:

  • running this workflow
  • or pushing a semver tag
    • signed tags are preferred
    • The tag message is prepended to release notes

Documentation

Overview

Package loads provides document loading methods for swagger (OAI v2) API specifications.

It is used by other go-openapi packages to load and run analysis on local or remote spec documents.

Loaders support JSON and YAML documents.

Index

Examples

Constants

View Source
const (
	// ErrLoads is an error returned by the loads package.
	ErrLoads loaderError = "loaderrs error"

	// ErrNoLoader indicates that no configured loader matched the input.
	ErrNoLoader loaderError = "no loader matched"
)

Variables

This section is empty.

Functions

func AddLoader

func AddLoader(predicate DocMatcher, load DocLoader)

AddLoader for a document, executed before other previously set loaders.

This sets the configuration at the package level.

Concurrency

This function updates the default loader used by github.com/go-openapi/spec. Since this sets package level globals, you shouldn't call this concurrently.

func JSONDoc

func JSONDoc(path string, opts ...loading.Option) (json.RawMessage, error)

JSONDoc loads a json document from either a file or a remote URL.

See loading.Option for available options (e.g. configuring authentication, headers or using embedded file system resources).

Types

type DocLoader

type DocLoader func(string, ...loading.Option) (json.RawMessage, error)

DocLoader represents a doc loader type.

type DocLoaderWithMatch added in v0.20.0

type DocLoaderWithMatch struct {
	Fn    DocLoader
	Match DocMatcher
}

DocLoaderWithMatch describes a loading function for a given extension match.

func NewDocLoaderWithMatch added in v0.20.0

func NewDocLoaderWithMatch(fn DocLoader, matcher DocMatcher) DocLoaderWithMatch

NewDocLoaderWithMatch builds a DocLoaderWithMatch to be used in load options.

type DocMatcher

type DocMatcher func(string) bool

DocMatcher represents a predicate to check if a loader matches.

type Document

type Document struct {
	// specAnalyzer
	Analyzer *analysis.Spec
	// contains filtered or unexported fields
}

Document represents a swagger spec document.

func Analyzed

func Analyzed(data json.RawMessage, version string, options ...LoaderOption) (*Document, error)

Analyzed creates a new analyzed spec document for a root json.RawMessage.

func Embedded

func Embedded(orig, flat json.RawMessage, opts ...LoaderOption) (*Document, error)

Embedded returns a Document based on embedded specs (i.e. as a json.RawMessage). No analysis is required.

func JSONSpec

func JSONSpec(path string, opts ...LoaderOption) (*Document, error)

JSONSpec loads a spec from a JSON document, using the JSONDoc loader.

A set of loading.Option may be passed to this loader using WithLoadingOptions.

Example (Http_custom_header)

Loads a JSON document from http, with a custom header.

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"

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

func main() {
	ts := serveSomeJSONDocument()
	defer ts.Close()

	doc, err := loads.JSONSpec(ts.URL,
		loads.WithLoadingOptions(loading.WithCustomHeaders(map[string]string{
			"X-API-key": "my-api-key",
		})))
	if err != nil {
		panic(err)
	}
	fmt.Println(doc.Host())
	fmt.Println(doc.Version())

}

func serveSomeJSONDocument() *httptest.Server {
	source, err := os.Open(filepath.Join("fixtures", "json", "resources", "pathLoaderIssue.json"))
	if err != nil {
		panic(err)
	}

	return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
		rw.WriteHeader(http.StatusOK)
		_, _ = io.Copy(rw, source)
	}))
}
Output:

api.example.com
2.0

func Spec

func Spec(path string, opts ...LoaderOption) (*Document, error)

Spec loads a new spec document from a local or remote path.

By default it uses a JSON or YAML loader, with auto-detection based on the resource extension.

Example (Embedded_yaml)

Loads a JSON document from the embedded file system and get the deserialized spec.Swagger specification.

package main

import (
	"embed"
	"fmt"
	"path"

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

//go:embed fixtures
var embeddedFixtures embed.FS

func main() {
	// loads a YAML spec from a file on an embedded file system
	doc, err := loads.Spec(
		path.Join("fixtures", "yaml", "swagger", "spec.yml"), // [embed.FS] sep is "/" even on windows
		loads.WithLoadingOptions(
			loading.WithFS(embeddedFixtures),
		))
	if err != nil {
		panic(err)
	}

	fmt.Println(doc.Host())
	fmt.Println(doc.Version())

	spec := doc.Spec()
	if spec == nil {
		panic("spec should not be nil")
	}

}
Output:

api.example.com
2.0
Example (File)

Example with default loaders defined at the package level.

package main

import (
	"fmt"

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

func main() {
	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 (Http_json)

Loads a JSON document and get the deserialized spec.Swagger specification.

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"

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

func main() {
	ts := serveSomeJSONDocument()
	defer ts.Close()

	// loads a YAML spec from a http URL
	doc, err := loads.Spec(ts.URL)
	if err != nil {
		panic(err)
	}

	fmt.Println(doc.Host())
	fmt.Println(doc.Version())

	spec := doc.Spec()
	if spec == nil {
		panic("spec should not be nil")
	}

}

func serveSomeJSONDocument() *httptest.Server {
	source, err := os.Open(filepath.Join("fixtures", "json", "resources", "pathLoaderIssue.json"))
	if err != nil {
		panic(err)
	}

	return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
		rw.WriteHeader(http.StatusOK)
		_, _ = io.Copy(rw, source)
	}))
}
Output:

api.example.com
2.0
Example (Http_yaml)

Loads a YAML document and get the deserialized spec.Swagger specification.

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"

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

func main() {
	ts := serveSomeYAMLDocument()
	defer ts.Close()

	// loads a YAML spec from a http URL
	doc, err := loads.Spec(ts.URL)
	if err != nil {
		panic(err)
	}

	fmt.Println(doc.Host())
	fmt.Println(doc.Version())

	spec := doc.Spec()
	if spec == nil {
		panic("spec should not be nil")
	}

}

func serveSomeYAMLDocument() *httptest.Server {
	source, err := os.Open(filepath.Join("fixtures", "yaml", "swagger", "spec.yml"))
	if err != nil {
		panic(err)
	}

	return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
		rw.WriteHeader(http.StatusOK)
		_, _ = io.Copy(rw, source)
	}))
}
Output:

api.example.com
2.0

func (*Document) BasePath

func (d *Document) BasePath() string

BasePath the base path for the API specified by this spec.

func (*Document) Expanded

func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error)

Expanded expands the $ref fields in the spec Document and returns a new expanded Document.

func (*Document) Host

func (d *Document) Host() string

Host returns the host for the API.

func (*Document) OrigSpec

func (d *Document) OrigSpec() *spec.Swagger

OrigSpec yields the original spec.

func (*Document) Pristine

func (d *Document) Pristine() *Document

Pristine creates a new pristine document instance based on the input data.

func (*Document) Raw

func (d *Document) Raw() json.RawMessage

Raw returns the raw swagger spec as json bytes.

func (*Document) ResetDefinitions

func (d *Document) ResetDefinitions() *Document

ResetDefinitions yields a shallow copy with the models reset to the original spec.

func (*Document) Schema

func (d *Document) Schema() *spec.Schema

Schema returns the swagger 2.0 meta-schema.

func (*Document) Spec

func (d *Document) Spec() *spec.Swagger

Spec returns the swagger object model for this API specification.

func (*Document) SpecFilePath

func (d *Document) SpecFilePath() string

SpecFilePath returns the file path of the spec if one is defined.

func (*Document) Version

func (d *Document) Version() string

Version returns the OpenAPI version of this spec (e.g. 2.0).

type LoaderOption added in v0.20.0

type LoaderOption func(*options)

LoaderOption allows to fine-tune the spec loader behavior.

Example

Example with custom loaders passed as options.

package main

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

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

func main() {
	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"

func WithDocLoader added in v0.20.0

func WithDocLoader(l DocLoader) LoaderOption

WithDocLoader sets a custom loader for loading specs.

func WithDocLoaderMatches added in v0.20.0

func WithDocLoaderMatches(l ...DocLoaderWithMatch) LoaderOption

WithDocLoaderMatches sets a chain of custom loaders for loading specs for different extension matches.

Loaders are executed in the order of provided DocLoaderWithMatch 'es.

func WithLoadingOptions added in v0.23.0

func WithLoadingOptions(loadingOptions ...loading.Option) LoaderOption

WithLoadingOptions adds some loading.Option to be added when calling a registered loader.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL